为了帮助构建扩展模块,SWIG附带了支持库,您可以在自己的接口中包括这些支持文件。 这些文件通常定义新的SWIG指令或提供实用程序功能,这些功能可用于访问标准C和C ++库的一部分。 本章提供对当前支持的库文件集的参考。
8.2.2 carrays.i
该模块定义了有助于将普通C指针包装为数组的宏。 该模块不提供任何安全性或额外的包装层-它仅提供用于创建,销毁和修改原始C数组数据内容的功能。
%array_functions(type,name)
Creates four functions.
type *new_name(int nelements)
Creates a new array of objects of type type. In C, the array is allocated usingcalloc(). In C++, new [] is used.
type *delete_name(type *ary)
Deletes an array. In C, free() is used. In C++, delete [] is used.
type name_getitem(type *ary, int index)
Returns the value ary[index].
void name_setitem(type *ary, int index, type value)
Assigns ary[index] = value.
使用此宏时,type可以是任何类型,并且名称必须是目标语言中的合法标识符。 名称不应该与接口文件中使用的任何其他名称对应。
%array_functions()的例子:
void print_array(double x[10]) {
int i;
for (i = 0; i < 10; i++) {
printf("[%d] = %g\n", i, x[i]);
}
}
打包它,可能会这样写
%module example %include "carrays.i" %array_functions(double, doubleArray); void print_array(double x[10]);
现在,脚本调用
a = new_doubleArray(10) # Create an array
for i in range(0,10):
doubleArray_setitem(a,i,2*i) # Set a value
print_array(a) # Pass to C
delete_doubleArray(a) # Destroy array
%array_class(type,name)
在基于类的接口内包装*类型的指针。 该界面如下:
struct name {
name(int nelements); // Create an array
~name(); // Delete array
type getitem(int index); // Return item
void setitem(int index, type value); // Set item
type *cast(); // Cast to original type
static name *frompointer(type *); // Create class wrapper from
// existing pointer
};
使用此宏时,类型被限制为简单的类型名称,例如int或float。 不允许使用指针和其他复杂类型。 名称必须是尚未使用的有效标识符。 将指针包装为类时,可以将其透明地传递给任何需要该指针的函数。
与代理类结合使用时,%array_class()宏会特别有用。 例如:
%module example %include "carrays.i" %array_class(double, doubleArray); void print_array(double x[10]);
现在,脚本调用
import example
c = example.doubleArray(10) # Create double[10]
for i in range(0,10):
c[i] = 2*i # Assign values
example.print_array(c) # Pass to C
注意:这些宏不会将C数组封装在特殊的数据结构或代理中。 没有边界检查或任何形式的安全性。 如果需要,应该考虑使用特殊的数组对象而不是裸指针。
注意:%array_functions()和%array_class()不应与char或char *类型一起使用。
8.4.1 std_string.i
std_string.i库提供了用于将C ++ std :: string对象与目标脚本语言在字符串之间进行转换的类型映射。 例如:
%module example %include "std_string.i" std::string foo(); void bar(const std::string &x);
在目标语言中
x = foo(); # Returns a string object
bar("Hello World"); # Pass string as std::string
常见问题是包含std :: string的类/结构的问题。 这可以通过定义类型映射克服。 例如:
%module example %include "std_string.i" %apply const std::string& {std::string* foo}; struct my_struct { std::string foo; };
目标语言中
x = my_struct();
x.foo="Hello World"; # assign with string
print x.foo; # print as string
该模块仅支持类型std :: string和const std :: string&。 指针和非const引用保持不变,并作为SWIG指针返回。
该库文件完全了解C ++名称空间。 如果导出std :: string或使用typedef重命名,请确保在接口中包括这些声明。 例如:
%module example %include "std_string.i" using namespace std; typedef std::string String; ... void foo(string s, const String &t); // std_string typemaps still applied