Swig - 为什么我们需要声明函数两次?

Swig - why we need to declare functions twice?

我想使用 swig 从 Java 调用 C 函数。 我读: SWIG Tutorial

并且网络包含接口文件示例:

/* example.i */
 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}

 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

为什么函数声明有重复? (例如 "extern int fact(int n);" 在 {% %} 和文件底部声明 ?

%{ %} 块中的内容被精确复制到生成的 c 文件 (example_wrap.c) 中,用作正向原型。块外的东西用于生成生成的 .c 文件内的函数。

一个更好的例子假设你已经有一个像 example.h 这样的头文件,其中包含如下内容:

extern void functionIwantToCallFromJava(int);
extern crazyType *functionIDoNotCareAbout(anotherCrazyType *);

所以在example.i里面你有

%{ 
#include "example.h"
%}
extern void functionIwantToCallFromJava(int);

现在生成的文件将在它需要的开头附近有 #include "example.h" 以便 functionIwantToCallFromJava 正确原型化, 但是 SWIG 不必生成大量代码来实现 functionIDoNotCareAbout,即使它是在同一个头文件中定义的。