简体   繁体   English

Python&C:是否可以将Ctypes和Swig混合在一起?

[英]Python & C: Is it possible to mix Ctypes and Swig together?

I am trying to find a way to test my C code using python scripts. 我试图找到一种使用python脚本测试我的C代码的方法。 So far my findings are 到目前为止,我的发现是

1) with Ctypes, I can easily load the so and call the function directly from python. 1)使用Ctypes,我可以轻松加载so并直接从python调用函数。 Plus, everything happens at run-time, so no extra compiling/wrapping stuff. 另外,一切都在运行时发生,因此没有多余的编译/包装内容。

2) However, re-writing every types in python is tedious and error prone, especially for complex data types. 2)但是,用python重写每种类型既乏味又容易出错,尤其是对于复杂的数据类型。 And whenever the definitions change, I will have to update the definition in python scripts. 并且每当定义更改时,我都必须在python脚本中更新定义。

I am wondering since Swig can export datatypes automatically, is it possible to mix Swig and Ctypes together? 我想知道既然Swig可以自动导出数据类型,是否可以将Swig和Ctypes混合在一起? ie use Swig to export datatypes, which can be used to call functions through Ctypes. 即使用Swig导出数据类型,该数据类型可用于通过Ctypes调用函数。

ps I am not sure whether Cython suits better, but we don't have Cython in the environment. ps我不确定Cython是否更合适,但是我们的环境中没有Cython。

I ended up using Swig with dynamic linking to the so library generated by the C code. 我最终使用Swig并动态链接到C代码生成的so库。 In this way, I only have to include the header files in the swig interface file to tell swig what functions/datatypes to expose. 这样,我只需要在swig接口文件中包含头文件即可告诉swig公开哪些函数/数据类型。 Another advantage of this approach is that I can write testing helper functions in C and easily expose those as well. 这种方法的另一个优点是,我可以用C编写测试帮助程序函数,也可以轻松地公开它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM