Search code examples
pythoncdllctypes

Trying to open a dll written in c with python ctypes and run the function in it, but it comes as int, not a string


These are my example source code:

C

#include <stdio.h>
#include <stdlib.h>

__declspec(dllexport)
char* sys_open(char* file_name)
{
    char *file_path_var = (char *) malloc(100*sizeof(char));

    FILE *wrt = fopen(file_name, "r");
    fscanf(wrt, "%s", file_path_var);
    fclose(wrt);

    return file_path_var;
}

Test.txt

test

Python

from ctypes import *

libcdll = CDLL("c.dll")
taken_var = libcdll.sys_open("test.txt")
print("VAR: ", taken_var)

Result

VAR: 4561325

So I'm just getting a random number. What should i do?


Solution

  • I found the true one.

    The python file was wrong, must be:

    from ctypes import *
    
    libcdll = CDLL("c.dll")
    taken_var = libcdll.sys_open("test.txt")
    print("VAR: ", c_char_p(taken_var).value)