0

This python code calls a dll(Created in LabVIEW) which returns the size of the string passed as argument. Every time I try passing string with different size, it returns the size as "1". I tried calling the dll in different programming languages like C,LabVIEW, it's working fine.

download link for dll file: 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)

Can anyone help me solve this?.Thanks in advance.

Prabakar
  • 174
  • 2
  • 4
  • 14
  • What does `SetExcursionFreeExecutionSetting` do? Also do you have the functions headers? I have an idea why it behaves like this but I want to test before making it public. Although I'm a bit reluctant executing unknown code on my *PC*. How do you call the func from other languages? – CristiFati Feb 28 '18 at 13:04

1 Answers1

1

Notes:

My guess was correct: the function expects a char * (8bit), while wchar\t * is 16bit.

Test code (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)))

Output:

(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

Explanation:

CristiFati
  • 38,250
  • 9
  • 50
  • 87