天天看点

ctypes python,python与c ++使用ctypes

ctypes python,python与c ++使用ctypes

As I'm still new to this, I'm facing some problems, here's my C++ code:

#include

#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT PyObject *Add(PyObject *pSelf, PyObject *pArgs)

{

int s,d;

if(!PyArg_ParseTuple(pArgs, "ii" , &s, &d))

{

PyErr_SetString(PyExc_TypeError,

"Add() invalid parameter");

return NULL;

}

return Py_BuildValue("i", s + d);

}

And the Python code:

import ctypes

MyDll = ctypes.cdll.LoadLibrary(r"PyToCppTest.dll")

jj = MyDll.Add(1,2)

I get an error when I run the above Python code:

OSError: exception: access violation reading 0x000000000000000A

I want to pass the data, without converting it, from Python to C++, then convert it inside C++.

解决方案

There are a few things that are wrong with your code. First and foremost, the proper include is:

#include

Note the capital P. You're probably on Windows, but this wouldn't work on Linux without the capital P.

Also, I don't see the point of the *pSelf pointer in your function declaration, you should get rid of it:

PyObject *Add(PyObject *pArgs)

Now, your main problem is this:

MyDll.Add(1,2)

...does not call MyDll.Add with a tuple. It calls it with two integer arguments, 1 and 2. If you want to pass a tuple, you'd do:

MyDll.Add((1,2))

However, Python's ctypes won't know what to do with this (it normally accepts integer arguments), so you'll need to tell it that Add actually wants a tuple, and returns a Python object:

import ctypes

MyDll = ctypes.cdll.LoadLibrary("PyToCppTest.dll")

MyCFunc = ctypes.PYFUNCTYPE(

ctypes.py_object, # return val: a python object

ctypes.py_object # argument 1: a tuple

)

MyFunc = MyCFunc(('Add', MyDll))

jj = MyFunc((1,2))