我想知道是否有办法在python代码中使用c ++函数
例如,经过研究后,我确实使用.dll文件找到了该解决方案。但是找不到功能我的代码:
fun.cpp:
#include <iostream>
extern int add(int a, int b) {
return a+b;
}
int main()
{
std::cout << "Hello World! from C++" << std::endl;
return 0;
}
使用cmd进行编译:
g ++ fun.cpp -o fun.dll
使用Python,ctypes调用函数:
from ctypes import *
import os
mydll = cdll.LoadLibrary("C:/Users/User/Desktop/ctypes/fun.dll")
result= mydll.add(10,1)
print("Addition value:-"+result)
但是我有这个错误:
追踪(最近一次通话):文件“ c:\ Users \ User.vscode \ extensions \ ms-python.python-2019.10.41019 \ pythonFiles \ ptvsd_launcher.py”,第43行main(ptvsdArgs)文件“ c:\ Users \ User.vscode \ extensions \ ms-python.python-2019.10.41019 \ pythonFiles \ lib \ python \ old_ptvsd \ ptvsd__main __。py”,主线432run()文件“ c:\ Users \ User.vscode \ extensions \ ms-python.python-2019.10.41019 \ pythonFiles \ lib \ python \ old_ptvsd \ ptvsd__main __。py”,在run_file中的第316行runpy.run_path(target,run_name ='main')文件“ C:\ Python36 \ lib \ runpy.py”,行263,在run_path中pkg_name = pkg_name,script_name = fname)文件“ C:\ Python36 \ lib \ runpy.py”,第96行,在_run_module_code中mod_name,mod_spec,pkg_name,script_name)文件“ C:\ Python36 \ lib \ runpy.py”,第85行,使用_run_codeexec(code,run_globals)文件“ c:\ Users \ User \ Desktop \ ctypes \ test.py”,第5行,在result = mydll.add(10,1)文件[C:\ Python36 \ lib \ ctypes__init __。py“,第361行,位于[[getattrfunc = self。getitem(名称)文件“ C:\ Python36 \ lib \ ctypes__init __。py”,行366,位于getitem中func = self._FuncPtr(((name_or_ordinal,self))AttributeError:函数'add'找不到
__declspec(dllexport)
。需要使用extern "C"
来使用C约定而不是名称混杂的C ++约定导出函数名称。由于C ++可以具有多个具有相同名称但采用不同参数的函数,因此在C ++中需要名称转换以指示函数参数和返回类型。 C约定不支持多个具有相同名称的函数。fun.cpp:
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
extern "C" API int add(int a, int b) {
return a+b;
}
Python:
from ctypes import * dll = CDLL('fun') result = dll.add(10,1) print('Addition value:',result)
输出:
Addition value: 11
LoadLibrary
是否正确调用了“ fun.dll”的main()
函数。加载时,它应该寻找DllMain()
函数,然后您需要获取函数地址才能调用该函数。