原因:由于涉及到通过python进行我们自己的dll调用,故查看了一下python关于dll的调用流程在此记录。
概述:目前验证python只能调用c风格的接口,我们常规的类方法是不能直接调用的,如果需要调用,则可以通过再次将类方法导出即可。
关于dll接口的导出我们涉及到两种定义格式,stdcall和cdecl两种,不同的导出约定python对应不同的调用方法。二者区别在此不进行阐述,简单的调用逻辑如下:首先定义一个dll如下
extern "C" __declspec(dllexport) int __cdecl Add(int i, int i2);
python的调用如下:可以看出由于是cdecl约定故使用CDLL方法。而且还要注意dll的版本类型(x64或者32)
from ctypes import *
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print("Hi, {0}".format(name)) # Press Ctrl+F8 to toggle the breakpoint.
pDll = CDLL("D:\\qwstone_test\\VS2019\\Dll_Python\\x64\\Debug\\Dll_Python.dll")
print pDll.Add(1,2)
那么如果我们定义一个类的话该如何调用,通过下面两种方式定义了一个可以调用的类,第一种是通过返回一个实例,第二种直接将类导出。
class PythonClass {
public:
int add(int i, int i2);
};
extern "C" __declspec(dllexport) PythonClass *CreateInstance();
或者
class __declspec(dllexport) PythonClass {
public:
int add(int i, int i2);
};
python调用如下:可以看出创建实例成功但是调用内部成员函数不可以.
from ctypes import *
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print("Hi, {0}".format(name)) # Press Ctrl+F8 to toggle the breakpoint.
pDll = CDLL("D:\\quanwei_test\\VS2019\\Dll_Python\\x64\\Debug\\Dll_Python.dll")
p = pDll.CreateInstance()
print p.add(1,2)//错误
所以python如果想要调用的话需要将类的接口进行再次导出,如下:
extern "C" __declspec(dllexport) int add(PythonClass *p,int i,int i2);