简体   繁体   English

Swig包装了C ++数据类型?

[英]Swig wrap a c++ datatype?

This might be an easy question. 这可能是一个简单的问题。 How I can call c++ defined datatype UInt32 from python? 如何从python调用c ++定义的数据类型UInt32

test.cpp: test.cpp:

#include "test.h"
namespace test {  
    void test(UInt32 param) { std::cout << param << std::endl; }
}

test.h: test.h:

#include <ios>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <assert.h>
#include <cassert>
#include <cstddef>
#include <stddef.h>
namespace test {
    typedef std::uint32_t UInt32;
    void test(UInt32 param);
}

test.i: test.i:

%module test
%{
    #define SWIG_FILE_WITH_INIT
    #include "test.h"
%}
%include "test.h"    

error: 错误:

>>> import test
>>> test.test(1)
TypeError: in method 'test', argument 1 of type 'test::UInt32'

Use typemapping ( link ). 使用typemapping( link )。 The simplest should look like: 最简单的应如下所示:

%apply int { test::UInt32 };  

The problem here is that SWIG doesn't know what a type UInt32 "is." 这里的问题是SWIG不知道UInt32“是”什么类型。 For a normal C++ typedef, you can simply tell SWIG in your interface file using the %typedef command , eg: 对于普通的C ++ typedef,您可以使用%typedef命令简单地在接口文件中告诉SWIG,例如:

%inline %{
 typedef unsigned int size_t;
%}

The above solution, ie, %apply int{ UInt32 }; 上面的解决方案,即%apply int{ UInt32 }; is essentially using the SWIG typemaps library ( Typemaps.i ) to replace any instance of the argument of form UInt32 with int (which SWIG knows about by default). 本质上是使用SWIG typemaps库Typemaps.i )将int形式的UInt32参数的任何实例替换为int (SWIG默认知道)。 However, it doesn't necessarily preserve the unsigned properties. 但是,它不一定保留未签名的属性。 Here you may want to instead use %apply unsigned int { UInt32 }; 在这里,您可能要改用%apply unsigned int { UInt32 }; . (Note that you need to include Typemaps.i for this to work). (请注意,您需要包括Typemaps.i才能Typemaps.i起作用)。

Finally, if you need to be able to return the value (eg, you want to pass it by reference), you can use the form: 最后,如果您需要能够返回该值(例如,您想通过引用传递它),则可以使用以下形式:

%apply unsigned int *INOUT { UInt32 };

The way to go depends upon what you want to do. 要走的路要取决于你想做什么。 If you just need SWIG to understand a typedef as a "synonym" of a (primitive or derived) type SWIG already knows about, the typedef approach is sufficient. 如果您只需要SWIG来将typedef理解为SWIG已经知道的(原始或派生)类型的“同义词”,则typedef方法就足够了。 If you also need to control the behavior of how SWIG handles arguments (eg, you need to be able to pass/return values by reference), typemaps (provided by the %apply command) is the way to go. 如果还需要控制SWIG处理参数的行为(例如,您需要能够通过引用传递/返回值),则应该使用类型映射(由%apply命令提供)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM