Python中用Ctypes读取Dll的双c结构

2024-09-30 04:36:01 发布

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

关于这个问题我做了很多研究。。但是没有地方我也找不到。我试图通过调用c dll来调用双c结构。你知道吗

我的问题是,我用python声明“类结构”的方法正确吗?我没想到我就在路上。因为即使我想从dll调用的函数没有输出任何东西。你知道吗

VisualC++/C]

我试过写C语法代码

typedef sturct {
    int nBoardNum;
    struct{
        char  pBoardName[16];
        int   nBoardID;
    }BOARDINDEX[8];
}AAPBOARDINFO, *PAAPBOARDINFO;

HANDLE AcapOpen(char* cpBoardName, int nBoardNo, int nCh)

[Python]

我这样修改了Python语法。你知道吗

import ctypes as c

class BOARDINDEX(c.Structure):
    _field_ = [("nBoardName", c.c_char_p * 16),("nBoardID", c.c_int)]

class AAPBOARDINFO(c.Structure):
    _field_ = [("nBoardNum", c.c_int), ("BOARDINDEX", BOARDINDEX * 8)]

AapLib2 = c.WinDLL("AapLib2.dll")

BoardName = ["ABC","FWD","HGW"]
BoardNo = 0
ch = 1

output = Open(BoardName, BoardNo, ch)

def Open(BoardName, BoardNo, ch)

    func = AapLib2.AcapOpen
    func.argtypes = [c.POINTER(BOARDINDEX),c.c_int, c.c_int]
    func.restype = c.c_int

    ref = BOARDINDEX()

    res = func(c.byref(ref.nBoardName),BoardNo, ch)
    return res

调用Open()函数时没有结果。。。你知道吗

请考虑我的要求和任何答复将是伟大的。。。你知道吗


Tags: 函数语法opench结构intfuncdll
1条回答
网友
1楼 · 发布于 2024-09-30 04:36:01

你需要知道的一切,都可以在[Python 3.Docs]: ctypes - A foreign function library for Python中找到。你知道吗

代码有几个问题:

这是您的代码的修改版本。不用说,我实际上没有测试它,因为我没有.dll: 你知道吗

#!/usr/bin/env python3

import sys
import ctypes
from ctypes import wintypes


class BOARDINDEX(ctypes.Structure):
    _fields_ = [
        ("nBoardName", ctypes.c_char * 16),
        ("nBoardID", ctypes.c_int),
    ]


class AAPBOARDINFO(ctypes.Structure):
    _fields_ = [
        ("nBoardNum", ctypes.c_int),
        ("BOARDINDEX", BOARDINDEX * 8),
    ]


def open_board(board_name, board_no, ch):
    AcapOpen = aaplib2.AcapOpen
    AcapOpen.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
    AcapOpen.restype = wintypes.HANDLE
    ref = BOARDINDEX(board_name, board_no)  # Probably this line should be replaced by the 3 (commented) ones below (AcapGetBoardInfo prototype would have to be specified as well)
    #abi = AAPBOARDINFO()
    #AcapGetBoardInfo(ctypes.byref(abi))
    #ref = abi.BOARDINDEX[0]
    res = AcapOpen(ref.nBoardName, ref.nBoardID, ch)
    return res


def main():
    board_names = ["ABC", "FWD", "HGW"]
    board_no = 0
    ch = 1
    aaplib2 = ctypes.WinDLL("AapLib2.dll")
    output = open_board(board_names[0], board_no, ch)
    print(output)


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    main()
    print("\nDone.")

告诉我这对你有什么好处。你知道吗

相关问题 更多 >

    热门问题