且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 C++ 函数导入 Python 程序

更新时间:2023-02-12 15:49:19

这里是上面简单示例的一个小工作完成.虽然帖子老了,但是我觉得给初学者一个简单的包罗万象的指南还是有帮助的,因为我之前也遇到过一些问题.

Here is a little working completion of the simple example above. Although the thread is old, I think it is helpful to have a simple all-embracing guide for beginners, because I also had some problems before.

function.cpp 内容(使用 extern "C" 以便 ctypes 模块可以处理函数):

function.cpp content (extern "C" used so that ctypes module can handle the function):

extern "C" int square(int x)
{
  return x*x;
}

wrapper.py 内容:

wrapper.py content:

import ctypes
print(ctypes.windll.library.square(4)) # windows
print(ctypes.CDLL('./library.so').square(4)) # linux or when mingw used on windows

然后编译function.cpp文件(例如使用mingw):

Then compile the function.cpp file (by using mingw for example):

g++ -shared -c -fPIC function.cpp -o function.o

然后使用以下命令创建共享对象库(注意:不是处处都是空白):

Then create the shared object library with the following command (note: not everywhere are blanks):

g++ -shared -Wl,-soname,library.so -o library.so function.o

然后运行wrapper.py,程序应该可以运行了.

Then run the wrapper.py an the program should work.