创建typedefd类型的变量我有痛饮项目设置生成Python代码。我有一个std::string
向typedef
和Message
一个say(Message)
功能。我可以用python中的字符串调用say
。我希望能够创建类型为Message
的变量,并且Message
类型被导出到库中,但不是python包装器。下面是我的文件:在痛饮
test.h
#include <string>
#include <iostream>
typedef std::string Message
void say(Message s);
TEST.CPP
#include "test.h"
void say(Message s)
{
std::cout << s << std::endl;
}
test.i
%module test
%{
#include "test.h"
%}
typedef std::string Message;
%include "std_string.i"
%include "test.h"
Python的例子
import test
test.say('a')
# >>> a
# What I want to be able to do
msg = test.Message('a')
# >>> Traceback (most recent call last):
# >>> File "<stdin>", line 1, in <module>
# >>> AttributeError: module 'test' has no attribute 'Message'
我的实际使用案例还涉及对其他类型(主要是枚举)的typedefs,如果这些案例采取了不同的处理方式,我很好奇。我相信我可以将对象包装在SWIG绑定的类中,然后修改SWIG生成的类(或者可以使用SWIG类型映射),但是我觉得这是一个迂回解决方案,我认为这是一种常见的情况。
我认为这可能是访问string
标题中的代码的问题,但如果我尝试敲入类似int
之类的东西,我会遇到同样的问题。
我的最好的方法,到目前为止已被包装的模板:
template<typename T>
class Wrapper
{
public:
Wrapper(T x) : data(x){};
T data;
T operator()() { return data; };
};
而且相应的%template
指令在test.i:
%template(Message) Wrapper<std::string>;
不幸的是,这似乎有几个缺点至今:
- 你必须实际LY打电话
operator()
,即需要test.Message('a')()
被称为 - 您需要可以选用一些条件编译或名称,包装的东西从不同的typedef;否则,
test.say
将不接受包装或字符串,因此根本无法使用。 - 它似乎并不与施工错误枚举工作。
我也认为我可能很聪明,并改变operator*
只是返回正在包装,但它看起来像SWIG包裹什么是返回无论如何。
我建议你使用'const char *',因为'std :: string'不是'POC'类型,并且内存分配在堆上,不管它是调试版本还是发行版本,其操作都是不同的。我预计通过包含'%include“std_string.i”'你可以创建一个'std :: string'实例。你有没有尝试过使用这个参数? –
我的预期是错误的,但我仍然建议您在界面上使用POC类型。 –
我希望能够将'%include std_string.i'或%import std_string.i'中的字符串实例化为'std_string.i'模板'string'作为'basic_string'。奇怪的是,这些似乎都没有导入一个可以创建实例的对象。也许这是因为SWIG似乎通过将字符串映射到目标语言字符串来处理字符串? –
danielunderwood