使用boost实现嵌入式python中的数组管理:从python到C和vicevers

2024-04-20 02:54:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我将嵌入Python脚本在我的C++应用程序中而不使用NUMPY库,我的问题是关于数组管理,如下面的代码:

class myclass 
{
    public:


        myclass()
        {

        }

        long PrintString(char* s)
        {
            printf("%s",s);
            return 0;
        }

        long PrintBytes(char* Buffer, long size)
        {
            for(int i=0; i < size; i++)
                printf("%d", Buffer[i]);
            return 0;
        }
};


int main()
{
    try
    {
        const char* lScript =   "from ctypes import *\n"
                                "s = 'Hello world!'\n"
                                "buff = (c_char * 16)()\n"
                                "myclassobj = myclass()\n"
                                "myclassobj.PrintString(s)\n"
                                "myclassobj.PrintBytes(buff,16)\n";

        object m_MainModule; 
        object m_MainNamespace;

        Py_Initialize();
        m_MainModule = import("__main__");
        m_MainNamespace = m_MainModule.attr("__dict__");


        m_MainNamespace["myclass"] = class_<myclass>("myclass")
                                    .def("PrintString"  ,   &myclass::PrintString)
                                    .def("PrintBytes"   ,   &myclass::PrintBytes) 
                                    ;

        handle<> ignored(PyRun_String(  lScript,
                                        Py_file_input,
                                        m_MainNamespace.ptr(),
                                        m_MainNamespace.ptr()       
                                    )
                        );  
    }
    catch( error_already_set ) 
    {
        PyErr_Print();
        getchar();
    }

}

当缓冲区数组返回以下错误时,字符串被正确管理:

Hello world!Traceback (most recent call last): File "", line 6, in Boost.Python.ArgumentError: Python argument types in myclass.PrintBytes(myclass, c_char_Array_16, int) did not match C++ signature: PrintBytes(class myclass {lvalue}, char *, long)

拜托,有人能帮我一个简单的解决办法吗?你知道吗

我的配置

  • python 2.7版
  • MSV C++ 2010
  • 增强\u 1 \u 55 \u 0
  • win7版本

Tags: sizereturnbuffermyclass数组longclassint