2012-09-09 44 views
3
#include <Python.h> 

static PyObject* helloworld(PyObject* self) 
{ 
    return Py_BuildValue("s", "Hello, Python extensions!!"); 
} 

static char helloworld_docs[] = 
    "helloworld(): Any message you want to put here!!\n"; 

static PyMethodDef helloworld_funcs[] = { 
    {"helloworld", (PyCFunction)helloworld, 
    METH_NOARGS, helloworld_docs}, 
    {NULL} 
}; 

void inithelloworld(void) 
{ 
    Py_InitModule3("helloworld", helloworld_funcs, 
        "Extension module example!"); 
} 

我一直在試圖用C擴展Python,因此一直試圖在Visual Studio中編譯上面的代碼。不過,我反覆出現以下錯誤:試圖從C調用Python

HiWorld.obj : error LNK2001: unresolved external symbol __imp__Py_BuildValue 
HiWorld.obj : error LNK2001: unresolved external symbol __imp__Py_InitModule4 

我一直停留在這個很長一段時間,並會:

LINK : fatal error LNK1104: cannot open file 'python27.lib' 

添加python27.lib的項目,然後我收到以下錯誤後非常感謝任何建議。

回答

0

假設你的代碼是正確的,最好的方法是使用setup.py文件。例如,這裏是當我創建一個Hello World模塊我用了一個的代碼:

setup.py:

from distutils.core import setup, Extension 

setup(
    ext_modules = [ 
     Extension("ext1", sources=["ext1.c"]), 
    ], 
) 

在這裏,「ext1"將被替換爲你的模塊的名字,而「」 EXT1 .c「的」會取代你的C源文件的名稱

然後你在終端上運行它像這樣:

setup.py install 

只是爲了進一步參考,在這裏是我的C源:

ext1.c:

#include "Python.h" 

static PyObject * 
hello_world(PyObject * self, PyObject * args) 
{ 
    return Py_BuildValue("s", "Hello World!"); 
} 

static PyMethodDef 
module_functions[] = { 
    { "hello_world", hello_world, METH_VARARGS, "Says Hello World."}, 
    { NULL } 
}; 

void 
initext1(void) 
{ 
    Py_InitModule3("ext1", module_functions, "My additional Module"); 
} 
0

這是連接問題,最常見的錯誤是關於forgotting,發行配置文件和調試配置文件使用不同的符號集,並作爲後果,只能成功鏈接到不同版本的庫;這意味着在調試模式下,您應該提供library-debugVersion.lib和版本library.lib

我也沒有太多使用Visual Studio,但我認爲更方便的將我需要的所有庫都放在公用文件夾中,類似C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\,因此VS可以自動爲您找到合適的庫,無論單個項目的設置是。