Reputation: 84
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.
Upvotes: 1
Views: 2606
Reputation: 177406
Here's one way to do it. I made some modifications to your non-working example:
%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]
Upvotes: 3