首页 > 解决方案 > 如何为 C 代码创建 python 接口?

问题描述

在我的研究领域有一个库,它是用 C 编写的。这个库的性能和准确性使其不可替代。然而,由于使用 C 语言,大多数人都很难处理这个包。

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

    #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);  
      ...
   }

我打算做的是通过创建一个创建C文件并运行它的翻译器来创建一个python接口,即如果用户键入import opr代码创建一个带有#include <opr/opr.h>主函数和初始化命令的C文件。

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

我听说 python 是很好的胶水语言,还听说像 numpy 这样的数字包使用一些 C 或 FORTRAN 库,我怎样才能使用这种胶水般的能力或像 numy 一样做类似的工作?

正如我之前提到的,该库的性能是独一无二的,并且不打算通过用 Python 语言编写它来重新发明轮子,除非可以对实际代码进行改进。

标签: pythoncwrapper

解决方案


下载 python 源代码并查看一些库扩展。您将了解事情的运作方式以及应该如何完成。


推荐阅读