Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法在Python和C之间传递结构_Python_C_Binding - Fatal编程技术网

有没有办法在Python和C之间传递结构

有没有办法在Python和C之间传递结构,python,c,binding,Python,C,Binding,我正在用C语言编写一个使用Python API的程序 Python将把输入(结构)传递给C程序,C程序将根据输入执行一些操作 有人能告诉我是否可以在Python和C之间传递结构。如果可以,请告诉我如何传递 我使用SWIG接口在C和Python之间传递值。示例程序运行良好(使用变量)。我已经添加了具有结构的代码,但我不确定用于该结构的代码格式。如果我做错了什么,请纠正我。我对Python和C完全陌生。我使用SWIG到处搜索传递结构,找不到任何正确答案 逻辑是从Python中获取输入值,并在c中执行

我正在用C语言编写一个使用Python API的程序

Python将把输入(结构)传递给C程序,C程序将根据输入执行一些操作

有人能告诉我是否可以在Python和C之间传递结构。如果可以,请告诉我如何传递

我使用SWIG接口在C和Python之间传递值。示例程序运行良好(使用变量)。我已经添加了具有结构的代码,但我不确定用于该结构的代码格式。如果我做错了什么,请纠正我。我对Python和C完全陌生。我使用SWIG到处搜索传递结构,找不到任何正确答案

逻辑是从Python中获取输入值,并在c中执行乘法运算,然后将值返回给Python

Sample.c
#include<stdio.h>
#include "sample.h"

struct info sample;

int getstruct (struct info sample);

int getstruct (struct info sample) {

   int i = 0;
   int j = 0;
   int k = 0;
   int l = 0;

   i = 2 * sample.i;
   j = 2 * sample.j;
   k = 2 * sample.k;
   l = 2 * sample.l;

   sample.i = i;
   sample.j = j;
   sample.k = k;
   sample.l = l;

   return(&sample);

}

sample.h
struct info
{
   int i;
   int j;
   int k;
   int l;
};

extern struct info data;

sample.i
%module sample
%{
#include "sample.h"
%}

%include "sample.h"

sample.py (automatically generated by SWIG)
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.11
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.





from sys import version_info
if version_info >= (2,6,0):
    def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_sample', [dirname(__file__)])
        except ImportError:
            import _sample
            return _sample
        if fp is not None:
            try:
                _mod = imp.load_module('_sample', fp, pathname, description)
            finally:
                fp.close()
            return _mod
    _sample = swig_import_helper()
    del swig_import_helper
else:
    import _sample
del version_info
try:
    _swig_property = property
except NameError:
    pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
    if (name == "thisown"): return self.this.own(value)
    if (name == "this"):
        if type(value).__name__ == 'SwigPyObject':
            self.__dict__[name] = value
            return
    method = class_type.__swig_setmethods__.get(name,None)
    if method: return method(self,value)
    if (not static):
        self.__dict__[name] = value
    else:
        raise AttributeError("You cannot add attributes to %s" % self)

def _swig_setattr(self,class_type,name,value):
    return _swig_setattr_nondynamic(self,class_type,name,value,0)

def _swig_getattr(self,class_type,name):
    if (name == "thisown"): return self.this.own()
    method = class_type.__swig_getmethods__.get(name,None)
    if method: return method(self)
    raise AttributeError(name)

def _swig_repr(self):
    try: strthis = "proxy of " + self.this.__repr__()
    except: strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)

try:
    _object = object
    _newclass = 1
except AttributeError:
    class _object : pass
    _newclass = 0


class info(_object):
    __swig_setmethods__ = {}
    __setattr__ = lambda self, name, value: _swig_setattr(self, info, name, value)
    __swig_getmethods__ = {}
    __getattr__ = lambda self, name: _swig_getattr(self, info, name)
    __repr__ = _swig_repr
    __swig_setmethods__["i"] = _sample.info_i_set
    __swig_getmethods__["i"] = _sample.info_i_get
    if _newclass:i = _swig_property(_sample.info_i_get, _sample.info_i_set)
    __swig_setmethods__["j"] = _sample.info_j_set
    __swig_getmethods__["j"] = _sample.info_j_get
    if _newclass:j = _swig_property(_sample.info_j_get, _sample.info_j_set)
    __swig_setmethods__["k"] = _sample.info_k_set
    __swig_getmethods__["k"] = _sample.info_k_get
    if _newclass:k = _swig_property(_sample.info_k_get, _sample.info_k_set)
    __swig_setmethods__["l"] = _sample.info_l_set
    __swig_getmethods__["l"] = _sample.info_l_get
    if _newclass:l = _swig_property(_sample.info_l_get, _sample.info_l_set)
    def __init__(self):
        this = _sample.new_info()
        try: self.this.append(this)
        except: self.this = this
    __swig_destroy__ = _sample.delete_info
    __del__ = lambda self : None;
info_swigregister = _sample.info_swigregister
info_swigregister(info)

# This file is compatible with both classic and new-style classes.

cvar = _sample.cvar


Error message:
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sample.py", line 28, in <module>
    _sample = swig_import_helper()
  File "sample.py", line 24, in swig_import_helper
    _mod = imp.load_module('_sample', fp, pathname, description)
ImportError: ./_sample.so: undefined symbol: data
>>>

Commands used:
swig -python sample.i
gcc -fPIC -c sample.c sample_wrap.c -I/usr/include/python2.7
ld -shared sample.o sample_wrap.o -o _sample.so
Sample.c
#包括
#包括“sample.h”
结构信息样本;
int getstruct(结构信息示例);
int getstruct(结构信息示例){
int i=0;
int j=0;
int k=0;
int l=0;
i=2*样本i;
j=2*sample.j;
k=2*sample.k;
l=2*sample.l;
样本i=i;
样本j=j;
样本k=k;
样本l=l;
退货(样品);
}
样本h
结构信息
{
int i;
int j;
int k;
int l;
};
外部结构信息数据;
样本i
%模块样本
%{
#包括“sample.h”
%}
%包括“sample.h”
sample.py(由SWIG自动生成)
#此文件由SWIG自动生成(http://www.swig.org).
#版本2.0.11
#
#除非您知道自己在做什么,否则不要对此文件进行更改--修改
#而不是SWIG接口文件。
从系统导入版本信息
如果版本信息>=(2,6,0):
def swig_import_helper():
从os.path导入目录名
进口小商品
fp=无
尝试:
fp,路径名,description=imp.find_模块(“_sample”,[dirname(u文件)]
除恐怖外:
进口样品
返回样本
如果fp不是无:
尝试:
_mod=imp.load_模块(“样本”,fp,路径名,描述)
最后:
fp.close()
返回模式
_示例=swig\u import\u helper()
del swig_导入帮助程序
其他:
进口样品
del版本信息
尝试:
_swig_属性=属性
除名称错误外:
pass#Python<2.2没有“属性”。
def_swig_setattr_非动态(自身、类类型、名称、值、静态=1):
if(name==“thishown”):返回self.this.own(值)
如果(名称==“此”):
如果类型(值)。\uuuu名称\uuuuu=='SwigPyObject':
self.\uuuu dict\uuuu[name]=值
返回
方法=类\类型。\开关\设置方法\获取(名称,无)
if方法:返回方法(self,value)
如果(非静态):
self.\uuuu dict\uuuu[name]=值
其他:
引发AttributeError(“您无法将属性添加到%s”%self)
定义开关设置属性(自身、类类型、名称、值):
返回非动态(self、class、type、name、value、0)
def_swig_getattr(自身、类别、名称):
if(name==“thisown”):返回self.this.own()
method=class\u type.\uuuuuu swig\u getmethods\uuuuuuu.get(名称,无)
if方法:返回方法(self)
提升属性错误(名称)
def_swig_repr(自我):
try:strthis=“代理”+self.this.\uu repr\uuuu()
除外:strthis=“”
返回“%”(self.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
尝试:
_对象=对象
_newclass=1
除属性错误外:
类_对象:pass
_newclass=0
类信息(\u对象):
__swig_setmethods_uuu={}
__setattr\uuuz=lambda self,name,value:\u swig\u setattr(self,info,name,value)
__swig_getmethods_uuu={}
__getattr\uuuz=lambda self,名称:\u swig\u getattr(self,info,name)
__repr\uuuu=\u swig\u repr
__swig_setmethods_u[“i”]=\u sample.info\u i_set
__swig_getmethods_uu[“i”]=\u sample.info\u i\u get
if\u newclass:i=\u swig\u属性(\u sample.info\u i\u get,\u sample.info\u i\u set)
__swig_setmethods_u[“j”]=\u sample.info\u j_set
__swig_getmethods_u[“j”]=\u sample.info\u j_get
if\u newclass:j=\u swig\u属性(\u sample.info\u j\u get,\u sample.info\u j\u set)
__swig_setmethods_uu[“k”]=\u sample.info\u k_set
__swig_getmethods_uuu[“k”]=\u sample.info\u k\u get
if\u newclass:k=\u swig\u属性(\u sample.info\u k\u get,\u sample.info\u k\u set)
__swig_setmethods_uu[“l”]=\u sample.info\u l_set
__swig_getmethods_uu[“l”]=\u sample.info\u l\u get
if\u newclass:l=\u swig\u属性(\u sample.info\u l\u get,\u sample.info\u l\u set)
定义初始化(自):
this=\u sample.new\u info()
try:self.this.append(this)
除外:self.this=this
__swig\u destroy\u=\u sample.delete\u info
__del_u;=lambda self:无;
info\u swigregister=\u sample.info\u swigregister
信息\u swigregister(信息)
#此文件与经典类和新样式类都兼容。
cvar=_sample.cvar
错误消息:
Python 2.7.6(默认,2014年3月22日,22:59:56)
[GCC 4.8.2]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>进口样品
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“sample.py”,第28行,在
_示例=swig\u import\u helper()
swig\u import\u helper中第24行的文件“sample.py”
_mod=imp.load_模块(“样本”,fp,路径名,描述)
ImportError:./\u sample.so:未定义符号:数据
>>>
使用的命令:
swig-python示例.i
gcc-fPIC-c样本.c样本包装.c-I/usr/include/python2.7
ld-共享示例.o示例\u包装.o-o\u示例.so
您可以退房

我自己使用它,可以确认它工作得很好。请查看以获取python示例

正在执行以下代码:

头文件:

#include<stdio.h>

typedef struct
{
   int i;
   int j;
   int k;
   int l;
} MyStruct;

extern MyStruct sample;

extern int getstruct (MyStruct sample);
接口文件:

%module example
%{
#include "example.h"
%}

%include "example.h"
编译和链接文件:

$ swig -python example.i
$ gcc -fPIC -c example.c example_wrap.c -I/usr/include/python2.7
$ gcc -lpython -shared example.o example_wrap.o -o _example.so
现在转到python:

>>> import example
>>> a = example.MyStruct
>>> dir(a)
['__class__', '__del__', '__delattr__', '__dict__', '__doc__', 
 '__format__', '__getattr__', '__getattribute__', '__hash__',
 '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
 '__repr__', '__setattr__', '__sizeof__', '__str__',
 '__subclasshook__', '__swig_destroy__', '__swig_getmethods__',
 '__swig_setmethods__', '__weakref__', 'i', 'j', 'k', 'l', 'this']
>>> a.i = 1
>>> a.j = 1
>>> a.k = 1
>>> a.l = 1
>>> example.getstruct(a)
1605330080
我不确定结果是什么(可能是样本地址?)


PS:我看了Lee Daniel Crocker的回复,值得考虑。

谢谢,我将检查swig。使用swig教程,我能够运行示例程序(仅使用变量)suc
>>> import example
>>> a = example.MyStruct
>>> dir(a)
['__class__', '__del__', '__delattr__', '__dict__', '__doc__', 
 '__format__', '__getattr__', '__getattribute__', '__hash__',
 '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
 '__repr__', '__setattr__', '__sizeof__', '__str__',
 '__subclasshook__', '__swig_destroy__', '__swig_getmethods__',
 '__swig_setmethods__', '__weakref__', 'i', 'j', 'k', 'l', 'this']
>>> a.i = 1
>>> a.j = 1
>>> a.k = 1
>>> a.l = 1
>>> example.getstruct(a)
1605330080