0

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?

SteryNomo
  • 25
  • 3
  • Does this answer your question? [Issue returning values from C function called from Python](https://stackoverflow.com/questions/11803121/issue-returning-values-from-c-function-called-from-python) – Joseph Sible-Reinstate Monica Apr 02 '21 at 18:09

2 Answers2

0

I'm not a C developer, but isn't sys_open returning a pointer?. Last time I checked pointers are WORD sized memory addresses in HEX, so it might make sense that python sees a numerical value in HEX and converts it to a decimal?. Maybe what you want to return from your C funcion is &file_path_var

xburgos
  • 381
  • 3
  • 10
  • nope i taking an error about it. warning: function returns address of local variable [-Wreturn-local-addr] – SteryNomo Apr 02 '21 at 11:50
  • Then the problem is clearer. Your C function is returning the memory address of a variable that's out fo scope already. This: https://stackoverflow.com/questions/6897914/c-warning-function-returns-address-of-local-variable And this: https://stackoverflow.com/questions/12380758/error-function-returns-address-of-local-variable Might clarify things – xburgos Apr 02 '21 at 11:58
0

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)
SteryNomo
  • 25
  • 3