.2.3 how to open document file in python
What I'm trying to do:
I want to build a simple compiler in C++ in Python 2.7.
This C-only code for the VM is written in C and compiled with a C compiler (i.e. gcc for instance) via the mingw-w64 compiler.
The objective is to be able to load some C source files at the time of the execution of the program and call the C functions exported by them via a python interpreter.
To make it more challenging, the C source code for the VM is not written in a very structured way (i.e. every C function is on a different C source file), therefore it's very difficult to find the exact code lines that I need to write to have my python script able to call the functions of the C source code via the python interpreter.
The example below is just an example, I actually need to do this in my project.
#include
int main(void)
{
printf("Hello, world!");
return 0;
}
I tried to compile this code as follows:
gcc -c -o hello.o hello.c
Now I want to run the program 'hello' at the time of the execution of my python script:
python hello.py
Unfortunately, the python interpreter doesn't seem to understand the C standard function calls, as when I run the code, the interpreter prints the following:
Hello, world!
AttributeError:'module' object has no attribute 'printf'
I know how to solve the problem using ctypes.h, but I was wondering if I can solve the problem with a pure python solution.
A:
I solved the problem in a different way.
For every function to be called from the python interpreter, I used the ctypes library, so the interpreter could call the function with a python interface.
Below you can find a sample of the code needed to call a function from the C source code:
import ctypes
# create the ctypes structure
my_typed_struct = ctypes.c_int
def my_function_1(a):
# create an int with the value of a
my_int = ctypes.c_int(a)
#
Related links:
Comments