Analysis of Python and C Mutual Calling Mutual Call
Use before use:
VC compiler
Python interpreter
If you don't install VC, you can go to a Microsoft website next C compiler, the address is as follows:
Http://download.microsoft.com/download/3/9/b/39bac755-0a1e-4d0b-b72c-3a158b7444c4/vctoolkitsetup.exe
After loading, add the following 2 macros in the environment variables.
Include
Lib
1, C in C. Python
#include
Int main (int Argc, char * argv [])
{
Py_initialize ();
Pyrun_SIMpleString ("from time import time, ctime / n"
"Print 'Today IS', CTIME (Time ()) / N");
PY_FINALIZE ();
Return 0;
}
Compile directly with the CL file name
2, generate a DLL with C, call with Python
C code: such as foo.c
#include
/ * Define the method table. * /
Static PyObject * foo_bar (PyObject * Self, PyObject * args);
Static pymethoddef fooomethods [] = {
{"bar", foo_bar, meth_varargs},
{Null, null}
}
/ * Here's the initialization function. We don't need to do anything
For Our Own Needs, But Python Needs That Method Table. * /
voidin ()
{
(void) PY_INITMODULE ("foo", fooomethods;
}
/ * Finally, let's do something ... involved ... as an example function. * /
Static PyObject * foo_bar (Pyobject * Self, PyObject * args)
{
CHAR * STRING;
Int Len;
IF (! Pyarg_Parsetuple (ARGS, "S", & string))
Return NULL;
Len = strlish (string);
Return Py_BuildValue ("I", LEN);
}
C definition file: foo.def
Exports
Initfoo
Compilation Foo.dll
CL-C foo.c;
Link foo.obj / dll /def :foo.def /out:foo.dll
Call in Python:
IMPORT FOO
Dir (foo)
...
You can see the result:
>>> Import Foo
>>> DIR (FOO)
['__doc__', '__file__', '__name__', 'Bar']
>>> ^ z
(Note: The article is simple, but it is very suitable for beginners, please also laugh :))