Passing reference from Python to c++ function wrapped with swig for return value

蓝咒 提交于 2019-12-08 04:32:08

问题


Disclaimer, I am a swig and python noob

I have my own c++ library and I am wrapping it to use in python with swig.

My c++ class is like this:

public MyCppClass()
{
public:
   void MyFunction(char* outCharPtr, string& outStr, int& outInt, long& outLong)
   {
         outCharPtr = new char[2];
         outCharPtr[0] = "o";
         outCharPtr[1] = "k";

         outStr = "This is a result";

         outInt = 1;

         outLong = (long)12345;
    }

}

Now I wrap this class using swig and say the module is called MyClass.

What I want to achieve in python is the following code (OR SAY PSEUDO CODE because if it was the code it would be working) and output:

import module MyClass
from MyClass import MyCppClass

obj = MyCppClass();

outCharPtr = "";
outStr = "";
outInt = 0;
outLong = 0;

obj.MyFunction(outCharPtr, outStr, outInt, outLong);

print(outCharPtr);
print(outStr);
print(outInt);
print(outLong);

The output I want is:

>>>Ok
>>>This is a result
>>>1
>>>12345

I am using python 3.4

I am really apologetic if this is something basic but I have already spent around 8 hours on the resolution and can't come up with anything.

Any help will be very appreciated.

Thanks.


回答1:


Here's one way to do it. I made some modifications to your non-working example:

example.i

%module example

%include <std_string.i>
%include <cstring.i>

%cstring_bounded_output(char* outCharPtr, 256)
%apply std::string& OUTPUT {std::string& outStr};
%apply int& OUTPUT {int& outInt};
%apply long& OUTPUT {long& outLong};

%inline %{

class MyCppClass
{
public:
   void MyFunction(char* outCharPtr, std::string& outStr, int& outInt, long& outLong)
   {
         outCharPtr[0] = 'o';
         outCharPtr[1] = 'k';
         outCharPtr[2] = '\0';

         outStr = "This is a result";

         outInt = 1;

         outLong = (long)12345;
    }

};

%}

Example use:

>>> import example
>>> c=example.MyCppClass()
>>> c.MyFunction()
['ok', 'This is a result', 1, 12345]


来源:https://stackoverflow.com/questions/30331791/passing-reference-from-python-to-c-function-wrapped-with-swig-for-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!