c++ - Python ctypes 调用简单的 c++ dll

标签 c++ python-2.7 ctypes

我真的很难使用 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()

关于c++ - Python ctypes 调用简单的 c++ dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17286044/

相关文章:

python - Image in Image with cvMatchTemplate - 但是怎么做呢?

python - (ctypes)msvcrt.printf 并在 python 中打印

python - 在 Python 中使用 ctypes 的回调中的 c_void_p 参数

Python mmap ctypes - 只读

c++ - 当我尝试对使用 New 函数启动的对象调用 delete 函数时,为什么会出现范围错误?

c++ - 无法将 std::unique_lock move 到结构中

c++ - 在文本流中用另一个字符串替换所有出现的字符串

c++ - 为什么我不能对 const 元素 vector 调用 Reserve?

python - 有效改变 scipy.spare.csr_matrix 的维度

linux - 在 CentOS 6 上制作 2.7.3 默认版本的 python