将参考从Python传递给c ++函数,使用swig作为返回值 [英] Passing reference from Python to c++ function wrapped with swig for return value

查看:451
本文介绍了将参考从Python传递给c ++函数,使用swig作为返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明,我是一个swig和python noob

Disclaimer, I am a swig and python noob

我有我自己的c ++库,我包装它使用在python swig。

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

我的c ++类如下:

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;
    }

}

现在我使用swig并且说模块被称为MyClass。

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

我想在python中实现的是以下代码(或SAY PSEUDO CODE,因为如果它是代码,它将工作)并输出:

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);

我想要的输出是:

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

我使用的是python 3.4

I am using python 3.4

我真的很抱歉,如果这是基本的,但我已经花了大约8小时的决议,不能提出任何东西。

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.

任何帮助将非常赞赏。

感谢。

推荐答案

。我对您的非工作示例做了一些修改:

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;
    }

};

%}

使用示例:

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

这篇关于将参考从Python传递给c ++函数,使用swig作为返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆