【问题标题】:Ctypes-String pointersCtypes-字符串指针
【发布时间】:2018-02-28 12:49:15
【问题描述】:

此 python 代码调用一个 dll(在 LabVIEW 中创建),它返回作为参数传递的字符串的大小。 每次我尝试传递不同大小的字符串时,它都会返回大小为“1”。 我试过用 C、LabVIEW 等不同的编程语言调用 dll,效果很好。

dll文件下载链接:https://drive.google.com/open?id=1pnYI6-SfUY3Cn6EeD4mWUO6dlEBH3DmN

    import ctypes
    from ctypes import windll, cdll,\
        c_wchar, c_size_t, c_ulonglong, c_wchar_p, c_void_p,\
        sizeof,\
        WinError
    try:
        dllhandle = ctypes.CDLL("Strlen.dll")
        print("Library Loaded")
    except Exception as e:
        print("Can't open DLL:",e)
    dllhandle.Strlen.argtypes = [ctypes.c_wchar_p]
    dllhandle.Strlen.restype = ctypes.c_int32
    data = "Hello"
    data_ptr = ctypes.c_wchar_p(data)
    print("Data Pointer:",data_ptr)
    length = dllhandle.Strlen(data_ptr)
    print("Data:",data)
    print("String Length:",length)

谁能帮我解决这个问题?提前谢谢。

【问题讨论】:

  • SetExcursionFreeExecutionSetting 是做什么的?你也有函数标题吗?我知道它为什么会这样,但我想在公开之前进行测试。虽然我有点不情愿在我的PC 上执行未知代码。其他语言怎么调用func?

标签: python pointers dll ctypes


【解决方案1】:

注意事项

我的猜测是正确的:该函数需要 char * (8bit),而 wchar\t *16bit

测试代码(code.py):

#!/usr/bin/env python3

import sys
from ctypes import CDLL,\
    c_int, c_char_p, c_wchar_p


WORDS = [
    "",
    "a",
    "q z",
    "asd\n",
    "12345",
    "qwertyuiop",
]


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    strlen_dll = CDLL("Strlen")
    strlen_func = strlen_dll.Strlen
    strlen_func.restype = c_int
    for word in WORDS:
        print("{:s}:\n    len: {:d}".format(repr(word), len(word)))
        strlen_func.argtypes = [c_char_p]
        print("    Strlen.Strlen(c_char_p): {:d}".format(strlen_func(word.encode())))
        strlen_func.argtypes = [c_wchar_p]
        print("    Strlen.Strlen(c_wchar_p): {:d}".format(strlen_func(word)))

输出

(py35x64_test) E:\Work\Dev\StackOverflow\q049030000>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32

'':
    len: 0
    Strlen.Strlen(c_char_p): 0
    Strlen.Strlen(c_wchar_p): 0
'a':
    len: 1
    Strlen.Strlen(c_char_p): 1
    Strlen.Strlen(c_wchar_p): 1
'q z':
    len: 3
    Strlen.Strlen(c_char_p): 3
    Strlen.Strlen(c_wchar_p): 1
'asd\n':
    len: 4
    Strlen.Strlen(c_char_p): 4
    Strlen.Strlen(c_wchar_p): 1
'12345':
    len: 5
    Strlen.Strlen(c_char_p): 5
    Strlen.Strlen(c_wchar_p): 1
'qwertyuiop':
    len: 10
    Strlen.Strlen(c_char_p): 10
    Strlen.Strlen(c_wchar_p): 1

解释

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多