用C扩展Python,但需要导入Time modu

2024-09-30 04:39:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试着用C语言运行Python脚本。 我研究过Python.org网站文档和遵循指南实现用C扩展Python,https://docs.python.org/2/extending/extending.html

我可以用这个设置运行一些简单的Python代码。 然而,我的Python程序需要使用时间模块,即导入时间,当我编译时,它抱怨不能导入模块时间。如何正确导入?我正在使用Python2.6。你知道吗

SystemVerilog代码如下所示

`timescale 1 ns/1 ns
module top;
      import "DPI-C" context task startPython();
      export "DPI-C" task sv_write;

   // Exported SV task.  Can be called by C,SV or Python using c_write
   task sv_write(input int data,address);
      begin
     $display("sv_write(data = %d, address = %d)",data,address);
      end
   endtask

   initial
     begin
    startPython();
    $display("DONE!!");
     end

endmodule

C代码如下所示

#include <Python.h>
#include "vpi_user.h"
#include "pythonEmbedded.h"

static PyObject * c_write(PyObject *self, PyObject *args) {
    int address,data;
    if(!PyArg_ParseTuple(args, "ii", &data, &address))
      return NULL;
    sv_write(address,data);
    return Py_BuildValue("");
}

static PyMethodDef EmbMethods[] = {
    {"c_write",c_write, METH_VARARGS,"c_write(data,address)"},
    {NULL, NULL, 0, NULL}
};

DPI_DLLESPEC
int startPython(){
    Py_Initialize();
    Py_InitModule("emb", EmbMethods);
    PyRun_SimpleString("import emb\n"
               "emb.c_write(0,1)\n");
    PyRun_SimpleString("import time\n");
    Py_Finalize();
    return 0;
}

错误消息如下:

# Loading ./pythonEmbedded.so
# run -all
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: /usr/lib64/python2.6/lib-dynload/timemodule.so: undefined symbol: PyExc_ValueError
# sv_write(data =           1, address =           0)
# DONE!!
#  quit -f
# End time: 06:41:05 on Feb 24,2016, Elapsed time: 0:00:01
# Errors: 0, Warnings: 0

编译代码的Makefile如下:

MTI_HOME = /apps/mentor/questasim
INCLUDE  = $(INCLIBC) -I/usr/include/python2.6 -I$(MTI_HOME)/include
CFLAGS   = -gstabs -Wall -fpic -shared
MTI_GCC  = /apps/mentor/questasim/gcc-4.7.4-linux_x86_64
COMPILER = $(MTI_GCC)/bin/gcc
LIBS     = -lc -lssl -lpthread -lm -ldl -lutil -lpython2.6

sim:    pythonEmbedded.h pythonEmbedded.so
        vsim -64 top -c -sv_lib pythonEmbedded -do "run -all; quit -f"

pythonEmbedded.h: pythonEmbedded.sv
        vlib work
        vlog -64 -sv -dpiheader pythonEmbedded.h pythonEmbedded.sv

pythonEmbedded.sv:

pythonEmbedded.so: pythonEmbedded.c
        $(COMPILER) $< $(CFLAGS) $(INCLUDE) $(LIBS) -o $@

Tags: 代码pyimporttaskdatasoincludeaddress

热门问题