簡體   English   中英

從C共享庫訪問python ctypes結構

[英]access python ctypes structure from c shared library

我寫了一個python代碼來將ctypes結構傳遞給c庫函數

python代碼:

from ctypes import *

class Info(Structure):
   _field_ = [("input",c_int),
              ("out",c_int)]

info = Info()

info.input = c_int(32)
info.out = c_int(121)

lib = CDLL("./sharedLib.so").getVal
a = lib(byref(info))

C代碼:

#include <stdio.h>

struct info{
    int input;
    int out;
};

void getVal(struct info *a){
    printf("in = %i \n", a->input);
    printf("out = %i \n", a->out);
}

使用命令編譯它: gcc -shared -fPIC -o sharedLib.so sharedLib.c

輸出:

in = 0 
out = 0 

我的問題是,為什么輸出與我在python代碼中設置的值不同。 有什么解決辦法嗎? 我在32位環境中

在ctypes結構定義中,您編寫了_field_而不是_fields_ 結果,這些字段不會轉換為C等效項。

嘗試添加:

lib.argtypes = [POINTER(Info)]

在調用lib之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM