Swig 包装一个 C++ 数据类型?
Swig wrap a c++ datatype?
这可能是一个简单的问题。我如何从 python?
调用 c++ 定义的数据类型 UInt32
test.cpp:
#include "test.h"
namespace test {
void test(UInt32 param) { std::cout << param << std::endl; }
}
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:
%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'
使用类型映射(link)。
最简单的应该是这样的:
%apply int { test::UInt32 };
这里的问题是 SWIG 不知道什么是 UInt32 类型 "is." 对于普通的 C++ typedef,您可以简单地在接口文件中告诉 SWIG using the %typedef
command,例如:
%inline %{
typedef unsigned int size_t;
%}
上述解决方案,即 %apply int{ UInt32 };
本质上是 using the SWIG typemaps library (Typemaps.i
),用 int
替换形式 UInt32
的参数的任何实例(默认情况下 SWIG 知道)。但是,它不一定保留未签名的属性。在这里您可能想改用 %apply unsigned int { UInt32 };
。 (请注意,您需要包含 Typemaps.i
才能正常工作)。
最后,如果您需要能够 return 值(例如,您想通过引用传递它),您可以使用以下形式:
%apply unsigned int *INOUT { UInt32 };
要走的路取决于你想做什么。如果您只需要 SWIG 将 typedef 理解为 SWIG 已经知道的(原始或派生)类型的 "synonym",则 typedef
方法就足够了。如果您还需要控制 SWIG 如何处理参数的行为(例如,您需要能够通过引用 pass/return 值),类型映射(由 %apply
命令提供)是可行的方法。
这可能是一个简单的问题。我如何从 python?
调用 c++ 定义的数据类型 UInt32test.cpp:
#include "test.h"
namespace test {
void test(UInt32 param) { std::cout << param << std::endl; }
}
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:
%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'
使用类型映射(link)。 最简单的应该是这样的:
%apply int { test::UInt32 };
这里的问题是 SWIG 不知道什么是 UInt32 类型 "is." 对于普通的 C++ typedef,您可以简单地在接口文件中告诉 SWIG using the %typedef
command,例如:
%inline %{
typedef unsigned int size_t;
%}
上述解决方案,即 %apply int{ UInt32 };
本质上是 using the SWIG typemaps library (Typemaps.i
),用 int
替换形式 UInt32
的参数的任何实例(默认情况下 SWIG 知道)。但是,它不一定保留未签名的属性。在这里您可能想改用 %apply unsigned int { UInt32 };
。 (请注意,您需要包含 Typemaps.i
才能正常工作)。
最后,如果您需要能够 return 值(例如,您想通过引用传递它),您可以使用以下形式:
%apply unsigned int *INOUT { UInt32 };
要走的路取决于你想做什么。如果您只需要 SWIG 将 typedef 理解为 SWIG 已经知道的(原始或派生)类型的 "synonym",则 typedef
方法就足够了。如果您还需要控制 SWIG 如何处理参数的行为(例如,您需要能够通过引用 pass/return 值),类型映射(由 %apply
命令提供)是可行的方法。