问题描述
我从并运行调用.cpp工作正常。现在,试图在IPython中加载这样的类型,如
import ctypes
lib = ctypes.WinDLL('MathFuncsDll。 dll')
在正确的文件夹中产生
UnicodeDecodeError:'ascii'编解码器无法解码28位字节0xe4:ordinal不在范围(128)
我该怎么改?嗯,这可能是Win 7 64bit,而有些32bit的DLL还是正确的?稍后我再检查一下。
ctypes
不能与C ++一起工作,MathFuncsDLL示例被写入。
相反,写入C或至少导出C接口:
#ifdef __cplusplus
externC{
#endif
__declspec(dllexport )double Add(double a,double b)
{
return a + b;
}
#ifdef __cplusplus
}
#endif
另请注意,调用约定默认为 __ cdecl
,因此使用 CDLL
而不是 WinDLL
(使用 __ stdcall
调用约定):
>>> import ctypes
>>> dll = ctypes.CDLL('server')
>>> dll.Add.restype = ctypes.c_double
>>> dll.Add.argtypes = [ctypes.c_double,ctypes.c_double]
>>> dll.Add(1.5,2.7)
4.2
I created the MathFuncsDll.dll from MSDN DLL example and running the calling .cpp worked fine. Now, trying to load this in IPython with ctypes like
import ctypes
lib = ctypes.WinDLL('MathFuncsDll.dll')
being in the correct folder yields
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 28: ordinal not in range(128)
Similarly in Python shell this yields
WindowsError: [Error 193] %1 is not a valid Win32 application
What should I change? Hm, it might be Win 7 64bit vs. some 32bit dll or something right? I'll check later when I've time again.
ctypes
doesn't work with C++, which the MathFuncsDLL example is written in.
Instead, write in C, or at least export a "C" interface:
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) double Add(double a, double b)
{
return a + b;
}
#ifdef __cplusplus
}
#endif
Also note that the calling convention defaults to __cdecl
, so use CDLL
instead of WinDLL
(which uses __stdcall
calling convention):
>>> import ctypes
>>> dll=ctypes.CDLL('server')
>>> dll.Add.restype = ctypes.c_double
>>> dll.Add.argtypes = [ctypes.c_double,ctypes.c_double]
>>> dll.Add(1.5,2.7)
4.2
这篇关于Python:简单的ctypes dll加载产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!