如何为C代码创建python接口?

问题描述 投票:1回答:1

[我的研究领域中有一个用C语言编写的库。该库的性能和准确性使其无法替代。但是,由于使用C语言,因此大多数人都很难处理此软件包。

使用此程序包需要使用C进行一些编码;您必须包含一个库,然后才能使用某些特定的数据结构,并且在库中定义了函数。例如,如下面的代码所示,必须包含一个库,在主库中对其进行初始化,然后添加实验并定义新的变量以计算卡方:

    #include <stdio.h>     /* Some regular libraries */
    ....

    #include <opr/opr.h>   /* the mentioned library */



    int main(int argc, char *argv[])
    { 
      /* Initialize That library */
      oprInit(argv[0]);

      /* Initialize the experiment  */
      oprAddExperiment("experiment number 1"); 


      /* Initialize parameter vector(s) */
      opr_params hypothesis_values = oprAllocer();
      opr_params theory_values = oprAllocer();

      oprDefine(hypothesis_values,theta12,theta13,theta23,deltacp,sdm,ldm);

      oprDefine(theory_values,theta12,theta13,theta23,deltacp,sdm,ldm);  

...


  for(y=0.0; y<10.0 ;y=y+0.2)
  {
      /* updating the values in each loop */
      /* calculation Chi squared */

      res=opr_chi2(hypothesis_values, theory_values);  
      ...
   }

[我的意图是通过创建一个翻译器来创建python接口,该翻译器创建C文件并运行它,即,如果用户键入import opr,则代码将使用#include <opr/opr.h>,主要功能和初始化来创建C文件命令。

我知道这类解决方案不是最好的,所以我想知道是否还有另一种干净且最佳的方式在python脚本中使用此库?

我听说python是很好的粘合语言,还听说过像numpy这样的数字包使用了一些C或FORTRAN库,我该如何使用这种粘合功能或像numy一样完成类似的工作?

[正如我之前提到的,库的性能是独特的,除非可以对实际代码进行可能的改进,否则不要通过用Python语言编写来重新发明轮子。

python c wrapper
1个回答
0
投票

下载python源,并查看一些库扩展。您将了解事情的工作方式以及应该如何做。

© www.soinside.com 2019 - 2024. All rights reserved.