[問題] 在C++中PyList_Size的問題

看板Python作者 (關公)時間9年前 (2016/12/01 15:47), 編輯推噓0(009)
留言9則, 4人參與, 最新討論串1/1
我用python import ctypes來讀取我用C++寫成的dll檔 有以下兩個問題不知如何解決 我的<List.py>檔都是這樣寫的 <List.py> import ctypes dll = ctypes.CDLL('List.dll') dll.test.restype = ctypes.py_object dll.test.argtypes = [ctypes.py_object] l=[1.11,2.22,3.33] print (dll.test(l)) 問題一: <List.cpp> #include <Python.h> #include <iostream> using namespace std; extern "C" { __declspec(dllexport) PyObject *test(PyObject *arg) { cout << "Number of items: " << endl; return Py_None; } } 這樣寫最後輸出會出現 "Number of items: " ,但是程式是沒有回應的停止運作。 如果改成return arg ,輸出會變成 "Number of items: "、[1.11,2.22,3.33],正常。 請問Py_None這樣用不對嗎? 問題二: <List.cpp> #include <Python.h> #include <iostream> using namespace std; extern "C" { __declspec(dllexport) PyObject *test(PyObject *arg) { cout << PyList_Size(arg, 1) << endl; cout << "Number of items: " << endl; return arg; } } 這樣寫最後輸出只出現OSerror,連 "Number of items: " 都沒有了 PyList_Size()這個語法應該是沒有錯的吧,為什麼還有OSerror 拜託大家幫我解答QQ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 182.235.49.198 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1480578440.A.5A0.html

12/01 16:26, , 1F
附註:我用Python 3.5
12/01 16:26, 1F

12/01 16:56, , 2F
PyList_Size是 len(list)吧? 你是想印出第一個元素嗎?
12/01 16:56, 2F

12/01 17:02, , 3F
function最後return那行改成 Py_RETURN_NONE
12/01 17:02, 3F

12/01 17:55, , 4F
我想得到這個list的長度,當然也想得到裡面的元素
12/01 17:55, 4F

12/01 21:21, , 5F
你去查 Py_None 的文件就寫得很清楚了, 加油好嗎...
12/01 21:21, 5F


12/01 21:28, , 7F
不好意思,因為我兩個方法都試過了QQ 還是停止回應
12/01 21:28, 7F

12/02 11:13, , 8F
如果是要用讓python使用c++寫好的函式庫,為何不用cython?
12/02 11:13, 8F

12/02 11:13, , 9F
方便又省事
12/02 11:13, 9F
文章代碼(AID): #1OFzM8MW (Python)
文章代碼(AID): #1OFzM8MW (Python)