[英]Pass Mutable String Array From Python to C
我對 C 和 ctypes 都是新手,但我似乎找不到如何做到這一點的答案,特別是對於 numpy 陣列。
C代碼
// Import/Export Macros
#define DllImport __declspec( dllimport )
#define DllExport __declspec( dllexport )
// Test function for receiving and transmitting arrays
extern "C"
DllExport void c_fun(char **string_array)
{
string_array[0] = "foo";
string_array[1] = "bar";
string_array[2] = "baz";
}
Python代碼
import numpy as np
import ctypes
# Load the DLL library...
# Define function argtypes
lib.c_fun.argtypes = [np.ctypeslib.ndpointer(ctypes.c_char, ndim = 2, flags="C_CONTIGUOUS")]
# Initialize, call, and print
string_array = np.empty((3,10),dtype=ctypes.c_char)
lib.c_fun(string_array)
print(string_array)
我確信還需要進行一些編碼/解碼,但我不確定如何/哪個。 謝謝!
僅解決問題的C
代碼部分...
如評論中所述,如果顯示的三個變量定義為char
arrays, C
不允許以這種方式賦值:
string_array[0] = "foo";
string_array[1] = "bar";
string_array[2] = "baz";
使用以下內容:
strcpy(string_array[0], "foo");
strcpy(string_array[1], "bar");
strcpy(string_array[2], "baz");
只要這個 function 的調用者為緩沖區預分配和釋放 memory,這部分解決方案現在至少在語法上是正確的。
但是如果字符串確實需要不可變才能與 Python 兼容,那么在調用者 function 中分配char **string_array
的參數可以傳遞一個3 例如:
char **string_array = malloc(3*sizeof(*string_array));//creates array of 3 pointers.
然后將其稱為:
c_fun(string_array);
這使您可以使用您的 DLL 調用,如原始帖子中所示。:
DllExport void c_fun(char **string_array)
{
//array of pointers being assigned to addresses of 3 string literals
string_array[0] = "foo";//these will now be immutable strings
string_array[1] = "bar";
string_array[2] = "baz";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.