问题描述
因为我还是新的,我面临一些问题,这里是我的C ++代码:
As I'm still new to this, I'm facing some problems, here's my C++ code:
#include <python.h>
#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);
}
而Python代码:
import ctypes
MyDll = ctypes.cdll.LoadLibrary(r"PyToCppTest.dll")
jj = MyDll.Add(1,2)
我在运行上述Python代码时遇到错误:
I get an error when I run the above Python code:
$ b b
我想传递数据,而不将其转换,从Python到C ++,然后在C ++中转换。
I want to pass the data, without converting it, from Python to C++, then convert it inside C++.
推荐答案
你的代码有一些错误。首先,合适的include是:
There are a few things that are wrong with your code. First and foremost, the proper include is:
#include <Python.h>
注意资本 P
。你可能在Windows上,但是这不会在没有资本P的Linux上工作。
Note the capital P
. You're probably on Windows, but this wouldn't work on Linux without the capital P.
此外,我没有看到 * pSelf
指针,你应该摆脱它:
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)
$ b b
...不用元组调用 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))
然而,Python的ctypes不知道该怎么做(通常接受整数参数)需要告诉它 Add
实际上想要一个元组,并返回一个Python对象:
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))
这篇关于python与c ++使用ctypes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!