我想编写一个由python调用的c共享库

我想编写一个由python调用的c共享库,python,c,shared-libraries,ctypes,Python,C,Shared Libraries,Ctypes,这是c‘hello world’代码 #include <stdio.h> void hello(void) { printf("Hello, World!\n"); } 这可以工作,它的输出 Hello, World! 但是现在我在c中添加了一个多线程函数 #include <stdio.h> #include <pthread.h> void hello(void) { printf("Hello, Wo

这是c‘hello world’代码

#include <stdio.h>
void hello(void) {
    printf("Hello, World!\n");
}
这可以工作,它的输出

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);
}


我的代码出了什么问题?

问题似乎是无法找到pthread的dll文件。编译依赖于pthreads的共享库时,这只会从创建的dll文件向该dll文件添加依赖项。调用LoadLibrary时,需要找到此二阶依赖项

我在Linux上,对Windows不太熟悉,但您可以在中查找它在何处搜索依赖项

在Linux上,我可以使用
gcc-shared threads.c-o libthre.so-fPIC-pthread
编译您的c代码,然后在python中运行它:

import ctypes
lib_th = ctypes.cdll.LoadLibrary("./libthre.so")
lib_th.hello()
lib_th.print_thread()
我还可以使用
ldd
验证它是否找到pthread库:

$ ldd libthre.so 
        linux-vdso.so.1 (0x00007ffe758ec000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd1cd62b000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fd1cdc1e000)
如果pthread库不在搜索目录中,我可以在编译/链接共享库时使用
rpath
指定它,或者在运行python程序时使用LD_library_PATH环境变量指定它。不过,这些在Windows中的工作方式不同,所以很遗憾,我无法确切地告诉您如何在Windows中工作。也许您可以尝试将pthread dll复制到与您自己的dll文件相同的文件夹中,就像测试一样

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
...
...
import ctypes
lib_th = ctypes.cdll.LoadLibrary("./libthre.so")
lib_th.hello()
lib_th.print_thread()
$ ldd libthre.so 
        linux-vdso.so.1 (0x00007ffe758ec000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd1cd62b000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fd1cdc1e000)