You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中用P/Invoke调用C库无法加载位置无关可执行文件如何解决

编译配置修正步骤
  • 第一步:修改C库源码
    删掉C代码中无用的main函数,动态共享库不需要可执行入口函数,保留导出的attachCurrentThreadToCore方法即可,修正后的源码参考:
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>

int attachCurrentThreadToCore(int core) {
    pthread_t thread = pthread_self();
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(core, &set);
    return pthread_setaffinity_np(thread, sizeof(cpu_set_t), &set);
}
  • 第二步:新增编译参数生成位置无关的动态共享库
    你当前编译输出的是普通可执行文件,没有生成动态库所需的位置无关代码段,使用GCC编译时需要添加如下参数:
    • -fPIC:生成位置无关代码,满足动态库加载要求
    • -shared:指定编译输出为动态共享库而非可执行文件
    • -pthread:链接pthread线程库,避免运行时依赖缺失
      参考编译命令:
    gcc -shared -fPIC -pthread -o libpthreadWrapper.so 你的C源码文件名.c
    
  • 第三步:修正.NET端DllImport配置
    Linux系统下动态库默认遵循lib{库名}.so的命名规则,你可以将生成的libpthreadWrapper.so放到程序运行目录,然后将DllImport声明修改为:
    [DllImport("pthreadWrapper")]
    private static extern int attachCurrentThreadToCore(int core);
    
    也可以直接填写.so文件的完整绝对路径,确保路径拼写正确。
  • 额外验证步骤
    编译完成后可以使用ldd libpthreadWrapper.so命令检查库的依赖是否完整,确认没有not found的依赖项即可正常调用。

内容的提问来源于stack exchange,提问作者Christopher von Blum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:36:03