我有 DLL,C++ 接口可以和他一起工作。在 bcb 中,msvc 可以正常工作。我想使用 Python 脚本来访问这个库中的函数。使用 Swig 生成 python 包。
文件setup.py
import distutils
from distutils.core import setup, Extension
setup(name = "DCM",
version = "1.3.2",
ext_modules = [Extension("_dcm", ["dcm.i"], swig_opts=["-c++","-D__stdcall"])],
y_modules = ['dcm'])
文件dcm.i
%module dcm
%include <windows.i>
%{
#include <windows.h>
#include "../interface/DcmInterface.h"
#include "../interface/DcmFactory.h"
#include "../interface/DcmEnumerations.h"
%}
%include "../interface/DcmEnumerations.h"
%include "../interface/DcmInterface.h"
%include "../interface/DcmFactory.h"
运行这些命令(python 与扩展名 .py 相关联)
setup build
setup install
使用这个 DLL
import dcm
f = dcm.Factory() #ok
r = f.getRegistrationMessage() #ok
print "r.GetLength() ", r.GetLength() #ok
r.SetLength(0) #access violation
在最后一个字符串上,我遇到了访问冲突。而且我使用输入参数对每个函数都有访问冲突。
DcmInterface.h(接口)
class IRegistrationMessage
{
public:
...
virtual int GetLength() const = 0;
virtual void SetLength(int value) = 0;
...
};
uRegistrationMessage.cpp(在 DLL 中实现)
class TRegistrationMessage : public IRegistrationMessage
{
public:
...
virtual int GetLength() const
{
return FLength;
}
virtual void SetLength(int Value)
{
FLength = Value;
FLengthExists = true;
}
...
};
工厂
DcmFactory.h(在客户端代码中使用 DLL)
class Factory
{
private:
GetRegistrationMessageFnc GetRegistration;
bool loadLibrary(const char *dllFileName = "dcmDLL.dll" )
{
...
hDLL = LoadLibrary(dllFileName);
if (!hDLL) return false;
...
GetRegistration = (GetRegistrationMessageFnc) GetProcAddress( hDLL, "getRegistration" );
...
}
public:
Factory(const char* dllFileName = "dcmDLL.dll")
{
loadLibrary(dllFileName);
}
IRegistrationMessage* getRegistrationMessage()
{
if(!GetRegistration) return 0;
return GetRegistration();
};
};