【发布时间】:2021-07-01 20:04:39
【问题描述】:
这是 c 'hello world' 代码
#include <stdio.h>
void hello(void) {
printf("Hello, World!\n");
}
我使用 clion IDE 和 gcc 编译器来编译代码。 生成一个“.dll”共享库
这是python代码
import ctypes
dy = ctypes.cdll.LoadLibrary(r'C:\Users\ssc\CLionProjects\cpython\cmake-build-debug\libcpython.dll')
dy.hello()
这可以工作,它的输出
Hello, World!
但现在我在 c 中添加了一个多线程函数
#include <stdio.h>
#include <pthread.h>
void hello(void) {
printf("Hello, World!\n");
}
void *f1()
{
for(int ct=0;ct<100;ct++)
{
printf("thread 1 %d\n",ct);
}
pthread_exit(0);
}
void *f2()
{
for(int ct=0;ct<100;ct++)
{
printf("thread 2 %d\n",ct);
}
pthread_exit(0);
}
void print_thread(){
pthread_t p1;
pthread_t p2;
pthread_create(&p1, NULL,f1,NULL);
pthread_create(&p2, NULL,f2,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
}
它可以编译成一个 dll 共享库 但是当我使用 python 调用时,它不能工作。 这是错误信息
C:\Users\ssc\AppData\Local\Programs\Python\Python39\python.exe C:/Users/ssc/CLionProjects/cpython/test.py
Traceback (most recent call last):
File "C:\Users\ssc\CLionProjects\cpython\test.py", line 2, in <module>
dy = ctypes.cdll.LoadLibrary(r'C:\Users\ssc\CLionProjects\cpython\cmake-buil
d-debug\libcpython.dll')
File "C:\Users\ssc\AppData\Local\Programs\Python\Python39\lib\ctypes\__init__.
py", line 452, in LoadLibrary
return self._dlltype(name)
File "C:\Users\ssc\AppData\Local\Programs\Python\Python39\lib\ctypes\__init__.
py", line 374, in __init__
self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'C:\Users\ssc\CLionProjects\cpython\cma
ke-build-debug\libcpython.dll' (or one of its dependencies). Try using the full
path with constructor syntax.
我将此代码添加到一个 c 可执行程序中。它可以工作
C:\Users\ssc\CLionProjects\untitled2\cmake-build-debug\untitled2.exe
thread 1 0
thread 2 0
thread 2 1
thread 2 2
thread 2 3
...
...
我的代码有什么问题?
【问题讨论】:
标签: python c shared-libraries ctypes