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

.NET 7下C#创建可被DllImport调用的DLL失败求助

如何创建可通过C# DllImport调用的DLL?

你当前的代码无法正常工作,因为EdiLibraryExample是普通的.NET托管类库,而DllImport仅适用于调用非托管DLL(如C/C++编译的原生DLL)或被标记为可导出给非托管代码的.NET方法。以下是两种可行的实现方案:

方案1:使用.NET 5+原生特性[UnmanagedCallersOnly](推荐)

步骤1:修改类库代码,标记可导出方法

更新EdiLibraryExample的代码,给要导出的方法添加UnmanagedCallersOnly特性,指定调用约定和入口点:

namespace EdiLibraryExample
{
    public class Class1
    {
        [System.Runtime.InteropServices.UnmanagedCallersOnly(
            EntryPoint = "Add", 
            CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
}

步骤2:发布自包含的原生DLL

.NET托管类库需要发布为自包含部署才能生成可被非托管调用的原生DLL:

  1. 打开终端,进入类库项目目录
  2. 执行发布命令(以x64平台为例):
dotnet publish -c Release -r win-x64 --self-contained true

发布完成后,在bin/Release/net7.0/win-x64/publish目录下会得到包含原生代码的EdiLibraryExample.dll。

步骤3:修改调用方代码

更新EdiUseDLL中的DLL路径,指向发布后的原生DLL:

using System;
using System.Runtime.InteropServices;

class Program
{
    const string Path = @"C:\Users\Maxim\Desktop\EdiUseDLL\EdiLibraryExample\bin\Release\net7.0\win-x64\publish\EdiLibraryExample.dll";
    [DllImport(Path, CallingConvention = CallingConvention.Cdecl)]
    public static extern int Add(int a, int b);

    static void Main()
    {
        int result = Add(5, 3);
        Console.WriteLine("Result of addition: " + result); 
    }
}

方案2:创建非托管C++ DLL

如果允许用C++编写DLL,可直接编译为原生非托管DLL:

C++ DLL代码示例

#include "pch.h"

// extern "C"避免名称修饰,__declspec(dllexport)标记方法为导出
extern "C" __declspec(dllexport) int Add(int a, int b)
{
    return a + b;
}

编译为对应平台(x64/x86)的DLL后,直接用你最初的EdiUseDLL代码调用即可,注意调用方和DLL的平台架构必须一致。

核心注意事项

  • 平台匹配:调用方项目和DLL必须使用相同的平台架构(如同时为x64),否则会出现加载错误。
  • 调用约定一致:DllImport中指定的CallingConvention必须和DLL方法的调用约定匹配(如均为Cdecl)。
  • 自包含部署:使用.NET特性方案时,必须发布为自包含,否则生成的DLL仍是纯托管程序集,无法被DllImport调用。

内容的提问来源于stack exchange,提问作者Maksym Shymchenko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:04:51