Python ctypes调用简单的c++dll

Python ctypes calling simple c++ dll

本文关键字:c++dll 简单 调用 ctypes Python      更新时间:2023-10-16

我真的很难用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 的奇怪返回值

请协助。

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

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