PyArray_SimpleNewFromData example
PyArray_SimpleNewFromData example
我知道这件事已经回答了很多次,我也读了文档,但我仍然不能清楚地理解这是如何工作的。例如,我无法理解如何在其参数中填充值。这些例子并不能很清楚地解释它(或者可能是我不能)。有人能帮我理解这个函数的参数是如何填充的吗?他们的价值观应该是什么?我必须在不重新分配内存的情况下将一个向量从c++传递给Python。非常感谢任何帮助。我已经被这个问题困扰了很多天了。
我正在实现的代码:
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs,*pXVec,*c, *xarr1;
int i;
float fArray[5] = {0,1,2,3,4};
//float *p = &fArray[0] ;
npy_intp m = 5;
//void* PyArray_GetPtr(PyArrayObject* aobj, npy_intp* ind)¶
// Initialize the Python Interpreter
Py_Initialize();
PySys_SetArgv(argc, argv);
// Build the name object
pName = PyString_FromString(argv[1]);
// Load the module object
pModule = PyImport_Import(pName);
printf("check0n");
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
printf("check1n");
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, argv[2]);
printf("check2n");
// if (PyCallable_Check(pFunc))
// {
// Prepare the argument list for the call
//xarr1 = PyFloat_FromDouble(xarr[1]);
printf("check3n");
c = PyArray_SimpleNewFromData(1,&m,NPY_FLOAT,(void *)fArray);
printf("check3n");
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0, c);
pValue = PyObject_CallObject(pFunc, pArgs);
if (pArgs != NULL)
{
Py_DECREF(pArgs);
}
//}
// else
// {
// PyErr_Print();
// }
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
函数为:
PyObject *
PyArray_SimpleNewFromData(
int nd,
npy_intp* dims,
int typenum,
void* data)
最后一个参数(
data
)是数据的缓冲区。第二个参数(
dims
)是一个缓冲区,它的每个表项是一个维度;所以对于1d数组,它可以是长度为1的缓冲区(甚至是整数,因为每个整数都是长度为1的缓冲区)由于第二个参数是一个缓冲区,第一个参数(
nd
)告诉它的长度第三个参数(
typenum
)表示类型
例如,假设您在x
:
创建数组,使用
int dims[1];
dims[0] = 4;
PyArray_SimpleNewFromData(1, dims, NPY_INT64, x)
创建2X2矩阵,使用
int dims[2];
dims[0] = dims[1] = 2;
PyArray_SimpleNewFromData(2, dims, NPY_INT64, x)
确保您堵塞了上述方法所带来的内存泄漏。我猜在上面的x
是一个类型为void *
的指针。
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Qt focusObjectChanged example?
- 运行命令 "rosbag play example.bag" 时出错。找不到与插件 rosbag/NoEncryptor 对应的库
- QWebSocket Hello World Example
- c++ Doxygen example and description
- Example of CDocument::ReleaseFile for MFC
- 找不到 int com.example.nimashahbazi.mooshak.EncryptingActivity.
- Qt example const_cast
- TensorFlow C++ example for Android
- 运行"OpenPose C++ API Tutorial - Example 3 - Body from image"失败
- _Unwind_RaiseException example
- std::none_of example from cppreference.com
- Microsoft AMP for C++ with Dr Dobbs example?
- 在macOSX上编译boost_asio/example/ssl/server.cpp可以在Linux上工作
- Example for LVM_SUBITEMHITTEST
- Example of C++ 11 std::chrono::duration
- 重写 contiki 源代码“example-mesh.c”以根据计时器值发送消息
- boost::algorithm::boyer_moore_search OO example
- FSEvents C++ Example
- example of embarcadero WindowHandleToPlatform c++