这可能是一个简单的问题。我如何从 python 调用 c++ 定义的数据类型 UInt32?
测试.cpp:
#include "test.h"
namespace test {
void test(UInt32 param) { std::cout << param << std::endl; }
}
测试.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);
}
测试.i:
%module test
%{
#define SWIG_FILE_WITH_INIT
#include "test.h"
%}
%include "test.h"
错误:
>>> import test
>>> test.test(1)
TypeError: in method 'test', argument 1 of type 'test::UInt32'
最佳答案
这里的问题是 SWIG 不知道 UInt32 是什么类型。对于普通的 C++ typedef,您可以简单地在接口(interface)文件中告诉 SWIG using the %typedef
command ,例如:
%inline %{
typedef unsigned int size_t;
%}
上述解决方案,即 %apply int{ UInt32 };
本质上是 using the SWIG typemaps library (Typemaps.i
) 将 UInt32
形式的参数的任何实例替换为 int
(SWIG 默认知道)。但是,它不一定保留未签名的属性。在这里你可能想要使用 %apply unsigned int { UInt32 };
。 (请注意,您需要包含 Typemaps.i
才能正常工作)。
最后,如果您需要能够返回值(例如,您希望通过引用传递它),您可以使用以下形式:
%apply unsigned int *INOUT { UInt32 };
要走的路取决于你想做什么。如果您只需要 SWIG 将 typedef 理解为 SWIG 已知的(原始或派生)类型的“同义词”,则 typedef
方法就足够了。如果您还需要控制 SWIG 如何处理参数的行为(例如,您需要能够通过引用传递/返回值),类型映射(由 %apply
命令提供)是一种方法去吧。
关于python - Swig 包装一个 C++ 数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45831550/