typedef 阻止 SWIG 确定 Counter 是它可以直接转换的未装箱类型。在没有其他信息的情况下,它将Counter 视为只能由库中的函数生成和使用的抽象对象类型。
您需要告诉 SWIG Counter 等价于内在 long 或 long long。
typemap 是 SWIG 的做法。此外,SWIG 语言本身提供了typedefs 来声明Counter 的等价性及其底层的内在类型。
这是它的工作原理。您应该能够轻松地将其转换为您的问题的解决方案:
// hacking.i
%module hacking
%{
// "Simulation" of the header included verbatim in the glue code.
#ifdef USE_LONGLONG_COUNTS
typedef unsigned long long Count; /* a count of something */
#else
typedef unsigned long Count; /* a count of something */
#endif
Count foo(Count count) { return count; }
%}
// The typemaps...
%typemap(in) Count n {
#ifdef USE_LONGLONG_COUNTS
$1 = ULL2INT($input);
#else
$1 = ULONG2INT($input);
#endif
}
%typemap(out) Count {
#ifdef USE_LONGLONG_COUNTS
$result = ULL2NUM($1);
#else
$result = ULONG2NUM($1);
#endif
}
// Now tell SWIG about the type equivalences and function prototype.
#ifdef USE_LONGLONG_COUNTS
typedef unsigned long long Count; /* a count of something */
#else
typedef unsigned long Count; /* a count of something */
#endif
Count foo(Count count);
请注意,如果定义了USE_LONGLONG_COUNTS,那么您使用的Ruby 必须支持long long 类型。并非所有人都这样做。
Typemap 功能强大,有很多选项。您没有提供足够的信息来为您的问题提供更具体的解决方案。在您提供更多内容之前,引用Ruby SWIG docs 几乎是所有可能的事情。
现在构建,制作一个文件:
# extconf.rb
require 'mkmf'
create_makefile('hacking')
并且(如果您需要unsigned long,请省略-DUSE_LONGLONGCOUNTS):
$ swig -c++ -DUSE_LONGLONG_COUNTS -ruby -o wrap.cpp hacking.i
$ ruby extconf.rb
$ make
compiling wrap.cpp
linking shared-object hacking.bundle
$ make install
/usr/bin/install -c -m 0755 hacking.bundle ...
$ irb
2.2.1 :001 > require 'hacking'
=> true
2.2.1 :002 > Hacking.foo(1234567890123454567)
=> 1234567890123454567