Extending & Embedding Python Using C - A Module Using Windows |
Written by Mike James | |||||||
Wednesday, 08 January 2025 | |||||||
Page 3 of 3
The command line that this generates to build the library is: cl.exe /Zi /EHsc /nologo /IC:/Users/user/AppData/ Local/Programs/Python/Python311/include C:\Users\user\Documents\projects\arith.c "/link /dll /OUT:arith.pyd /LIBPATH:C:/Users/user/AppData/ Local/Programs/Python/Python311/libs" This works and finds the necessary include files. This should now all work but the Intellisense prompting will still be showing an error in the editor. The Intellisense analysis of your code is controlled by the c_cpp_properties.json file. You can add an autogenerated file using the command C/C++: Edit Configurations (UI) from the command palette. To include the Python header you need to add the line: "C:/Users/user/AppData/Local/Programs/Python/ to the include path in c_cpp_properties.json giving: { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:/Users/user/AppData/Local/ Programs/Python/Python311/include/" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.22000.0", "compilerPath": "cl.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-msvc-x64" } ], "version": 4 } Now not only should the program compile, it should also show no errors in the editor. The best way to compile it is to use Terminal, Run Build Task as this doesn’t attempt to start or debug an executable. After the build you should find arith.pyd in the same folder as the program. If you see an error something like: fatal error LNK1112: module machine type you have started VS Code using the wrong Native Tool prompt. Testing the ModuleThe final check is to make sure that the new module can be used within a Python program. You can do this in VS Code.
Now you can add a new file to the project called test.py with the code: import arith print(arith.add(1,2)) print(dir(arith)) As the current project folder isn’t on the Python import path, Pylance will mark the import as an error. To put the current folder on the import path we need to use the extension settings command. Use the command File, Settings and then select Pylance in the list of extensions.
If you do this then the Pylance error on the import statement will vanish. When you run the program you should see: 3 Notice that the function has the standard methods as well as the custom add function. In chapter but not in this extract
Summary
Extending & Embedding Python Using CBy Mike JamesBuy from Amazon. ContentsPreface
<ASIN:B0CK3X93KF> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
|||||||
Last Updated ( Wednesday, 08 January 2025 ) |