1、C语言源码(main.c)
#include <stdio.h>
void test_loop()
{
for(int i=0; i<100; i++)
{
printf("C language: %d\n", i);
}
}
int main(){
printf("hello\n");
test_loop();
// getchar();
return 0;
// gcc -shared -o main.dll main.c
}
2、将main.c编译生成main.dll(略)
3、编写python代码运行C语言代码
from ctypes import *
""" 加载动态库 """
lib = cdll.LoadLibrary('./main.dll')
lib.test_loop() # 调用main.dll中的 test_loop 函数
"""
还可以使用多线程
from ctypes import *
from threading import Thread
# 加载动态库
lib = cdll.LoadLibrary(r'./main.dll')
# 创建一个子线程,让其执行C语言编写的函数
t = Thread(target=lib.test_loop)
t.start()
for i in range(10):
print('python次数: ', i)
"""