c++ - 为什么这个 extern "C"函数不能使用 python ctypes?

标签 c++ macos ctypes istringstream

我有以下使用字符串设置整数的 C++ 函数。

#include <sstream>
#include <string>
#include <iostream>
using namespace std;

extern "C" {
  int a() {
    int number;
    string value("100");
    std::istringstream strm(value);
    strm >> number;
    if (strm.fail()) {
      cout << "Ouch!" << endl;
    }
    else {
      cout << "Number set to:" << number << endl;
    };
    return (int)strm.bad();
  }
}

int main(int argc, char **argv)
{
  a();
}

如果我将其编译为一个程序,它就可以工作。

$ g++ ./streamtest.cc -o streamtest;./streamtest
Number set to:100

但是,如果我从 ctypes 调用相同的函数,它不会设置整数并且“strm”处于“错误”状态。

$ g++ -shared streamtest.cc  -o libstreamtest.so
$ python -c "import ctypes;a = ctypes.CDLL('libstreamtest.so').a();print 'Got [%s] from a()' %a"
Ouch!
Got [1] from a()

这让我很困惑。我怎样才能让这个函数在 ctypes 下工作?

最佳答案

它适用于使用 x86 构建的 Windows 7 (x64)。您是否尝试过用 C 包装代码以用作 Python 的模块?也许这对你有用..

C:\Users\niklas\Desktop>g++ -o streamtest.pyd -shared -I"C:\Python27\include" -L"C:\Python27\libs" streamtestmodule.cpp -lpython27


C:\Users\niklas\Desktop>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import streamtest
>>> streamtest.a()
Number set to:100
0

#include <Python.h>
#include "streamtest.cpp"

extern "C" {

static PyObject* streamtest_a(PyObject* self) {
    PyObject* re = Py_BuildValue("i", a());
    return re;
}

static PyMethodDef StreamtestMethods[] = {
    {"a", (PyCFunction) streamtest_a, METH_NOARGS, NULL},
    {NULL, NULL, 0, NULL}
};


void initstreamtest(void) {
    PyObject* module = Py_InitModule("streamtest", StreamtestMethods);
    if (module == NULL) {
        cout << "Module initialization failed.";
    }
}

} // extern "C"

关于c++ - 为什么这个 extern "C"函数不能使用 python ctypes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9502746/

相关文章:

c++ - Android 从 C++ 端播放原始音频

c++ - setter 和线程

c++ - 使用的C++程序堆栈大小何时确定?

java - 你能在 Java 中捕获 "package x does not exist"错误吗?

python - 如何将文件作为流从 python 发送到 C 库

windows - 在 python 上使用 ctypes 不显示多个消息框

c++ - 关于先序树遍历

objective-c - 如何监控 OS X 上的进程?

php - 无法在 Mac 上连接到 MySQL——缺少 mysql.sock 文件

python - 传递标准 :vector from C++ to Python via Ctypes: getting nonsensical values