为了解决这个问题,我创建了以下迷你头文件来演示我们(可能)真正关心的所有部分。我这样做的目标是:
- C# 用户甚至不应该意识到这里发生了任何非面向对象的事情。
- 您的 SWIG 模块的维护者不应该必须回应所有内容并尽可能手动编写大量代理函数。
为了开始,我编写了以下头文件 test.h:
#ifndef TEST_H
#define TEST_H
struct context;
typedef struct context context_t;
void init_context(context_t **new);
void fini_context(context_t *new);
void context_func1(context_t *ctx, int arg1);
void context_func2(context_t *ctx, const char *arg1, double arg2);
#endif
还有一个对应的带有一些存根实现的 test.c:
#include <stdlib.h>
#include "test.h"
struct context {};
typedef struct context context_t;
void init_context(context_t **new) {
*new = malloc(sizeof **new);
}
void fini_context(context_t *new) {
free(new);
}
void context_func1(context_t *ctx, int arg1) {
(void)ctx;
(void)arg1;
}
void context_func2(context_t *ctx, const char *arg1, double arg2) {
(void)ctx;
(void)arg1;
(void)arg2;
}
我们需要解决几个不同的问题才能将其变成一个简洁、可用的 OO C# 界面。我将一次解决一个问题,并在最后介绍我的首选解决方案。 (对于 Python,这个问题可以用更简单的方式解决,但这里的解决方案将适用于 Python、Java、C# 和可能的其他)
问题 1:构造函数和析构函数。
通常在 OO 风格的 C API 中,您会编写某种构造函数和析构函数来封装您的任何设置(可能是不透明的)。为了以合理的方式将它们呈现给目标语言,我们可以使用%extend 编写看起来很像 C++ 构造函数/析构函数,但在 SWIG 处理后仍以 C 形式出现。
%module test
%{
#include "test.h"
%}
%rename(Context) context; // Make it more C# like
%nodefaultctor context; // Suppress behaviour that doesn't work for opaque types
%nodefaultdtor context;
struct context {}; // context is opaque, so we need to add this to make SWIG play
%extend context {
context() {
context_t *tmp;
init_context(&tmp);
// we return context_t * from our "constructor", which becomes $self
return tmp;
}
~context() {
// $self is the current object
fini_context($self);
}
}
问题2:成员函数
我设置它的方式允许我们使用一个可爱的技巧。当我们说:
%extend context {
void func();
}
SWIG 然后生成一个如下所示的存根:
SWIGEXPORT void SWIGSTDCALL CSharp_Context_func(void * jarg1) {
struct context *arg1 = (struct context *) 0 ;
arg1 = (struct context *)jarg1;
context_func(arg1);
}
要消除的两件事是:
- 实现扩展
context::func调用的函数称为context_func
- 始终有一个隐含的“this”等效参数作为参数 1 进入此函数
上面的内容与我们开始在 C 端包装的内容非常吻合。所以要包装它,我们可以简单地做:
%module test
%{
#include "test.h"
%}
%rename(Context) context;
%nodefaultctor context;
%nodefaultdtor context;
struct context {};
%extend context {
context() {
context_t *tmp;
init_context(&tmp);
return tmp;
}
~context() {
fini_context($self);
}
void func1(int arg1);
void func2(const char *arg1, double arg2);
}
这并不像我希望的那样完全符合我的目标的第 2 点,您必须手动写出函数声明(除非您使用 %include 的技巧并保留它们的单个头文件)。使用 Python,您可以在导入时将所有部分组合在一起并使其更简单,但我看不到一种巧妙的方法来将所有与模式匹配的函数枚举到 SWIG 生成 .cs 文件的正确位置。
这足以让我使用以下代码进行测试(使用 Mono):
using System;
public class Run
{
static public void Main()
{
Context ctx = new Context();
ctx.func2("", 0.0);
}
}
有可能解决的other variants of C OO style design, using function pointers 和我过去解决过的类似问题looking at Java。