2

我真的很难使用 ctypes 从 python 调用一个简单的 c++ dll

下面是我的 C++ 代码:

#ifdef __cplusplus
extern "C"{
#endif
  __declspec(dllexport) char const* greet()
{
  return "hello, world";
}
#ifdef __cplusplus
}
#endif

...

我的 Python 代码:

import ctypes
testlib = ctypes.CDLL("CpLib.dll");
print testlib.greet();

当我运行我的 py 脚本时,我得到了这个奇怪的返回值 -97902232

请协助。

4

1 回答 1

3

您没有告诉 ctypes 返回值是什么类型,因此它假定它是一个整数。但它实际上是一个指针。设置 restype 属性让 ctypes 知道如何解释返回值。

import ctypes 
testlib = ctypes.CDLL("CpLib.dll")
testlib.greet.restype = ctypes.c_char_p
print testlib.greet()
于 2013-06-24T22:35:15.307 回答