首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有内联指令的SWIG、Python和接口文件

带有内联指令的SWIG、Python和接口文件
EN

Stack Overflow用户
提问于 2021-08-08 10:59:17
回答 1查看 183关注 0票数 1

我有Ubuntu-20.04,Anaconda-3 (安装在用户dir中),有Pythont-3.7.9和swg-4.0。

这是我的档案。

a.h

代码语言:javascript
复制
void foo(void);

a.c

代码语言:javascript
复制
#include <stdio.h>
#include "a.h"
void foo(void) { printf("Foo!\n"); }

a.i

代码语言:javascript
复制
%module a
%inline %{
#include "a.h"
%}

test.py

代码语言:javascript
复制
import a
a.foo()

编译脚本compile.sh

代码语言:javascript
复制
A=$HOME/opt/anaconda3
I=$A/include/python3.7m
gcc -c -fpic -DHAVE_CONFIG_H -I$I a.c
$A/bin/swig -python -py3 a.i
gcc -c -fpic -DHAVE_CONFIG_H -I$I a_wrap.c
gcc -shared a.o a_wrap.o -o _a.so

编译后,测试脚本将生成

代码语言:javascript
复制
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    a.foo()
AttributeError: module 'a' has no attribute 'foo'

但是,如果我编写一个更长的接口文件,那么一切都是可以的:

代码语言:javascript
复制
%module a
%{
#include "a.h"
%}
%include "a.h"

UPD @Jens建议在第一个(简称)接口文件中用%替换#。在这种情况下我得到了

代码语言:javascript
复制
a_wrap.c:2701:1: error: expected identifier or '(' before '%' token
 2701 | %include "a.h"
      | ^
a_wrap.c:2720:12: error: '_wrap_foo' undeclared here (not in a function)
 2720 |   { "foo", _wrap_foo, METH_NOARGS, NULL},
      |            ^~~~~~~~~
gcc: error: a_wrap.o: No such file or directory
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-09 00:22:46

%inline既包括直接包含在SWIG生成的包装代码中的大括号代码,也包括将其处理到生成的目标语言接口。所以这个:

代码语言:javascript
复制
%module a
%inline %{
void foo(void);
%}

相当于:

代码语言:javascript
复制
%module a
%{
void foo(void) {}
%}
void foo(void) {}

但这一点:

代码语言:javascript
复制
%module a
%inline %{
#include "a.h"
%}

相当于:

代码语言:javascript
复制
%module a
%{
#include "a.h"
%}
#include "a.h"  // NOT the same as %include "a.h" and isn't processed for interfaces

为了显示%inline既包括也被处理,我制作了:

代码语言:javascript
复制
%module a
%inline %{
#include "a.h"   // ignored in "include-in-wrapper" pass
#ifdef SWIG
%include "a.h"   // processed in "wrap-with-SWIG" pass
#endif
%}

上面的操作是正确的,并公开了接口,但它比仅仅使用:

代码语言:javascript
复制
%module a
%{
#include "a.h"
%}
%include "a.h"

%inline实际上用于向包装器中插入新函数并公开接口,如下所示:

代码语言:javascript
复制
%module a
%inline %{
class myClass
{
private: 
  int a;
public: 
  myClass(){} 
  void foo(){}
};
%}

否则,您必须至少编写以下内容:

代码语言:javascript
复制
%module a

%{ // new functionality added to wrapper
class myClass
{
private: 
  int a;
public: 
  myClass(){} 
  void foo(){}
};
%}

class myClass   // process the interface
{
public:         // note don't need to repeat private part or
  myClass();    // implementation, just public declarations to be exposed.
  void foo();
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68700101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档