我之前成功地使用了Unmanaged ExportsDllExport.NET DLL文件和Inno安装程序.

然而,现在我正试图让它与DNNE一起工作.

我有以下针对x86的C代码

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableDynamicLoading>true</EnableDynamicLoading>
    <Platforms>x86</Platforms>
    <RuntimeIdentifier>win-x86</RuntimeIdentifier>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="DNNE" Version="1.0.31" />
  </ItemGroup>

</Project>
using System.Runtime.InteropServices;

namespace DNNETest
{
    internal static class NativeMethods
    {
        [DllImport("User32.dll", EntryPoint = "MessageBox",
            CharSet = CharSet.Auto)]
        internal static extern int MsgBox(
            IntPtr hWnd, string lpText, string lpCaption, uint uType);
    }

    public class Class1
    {
        [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
        public static void Test()
        {
            _ = NativeMethods.MsgBox(IntPtr.Zero, "Hello from C#", ":)", 0);
            return;
        }
    }
}

我制作了一个小型控制台应用程序来验证导出的代码是否正常工作:

using System.Runtime.InteropServices;

NE.Test();

public static class NE
{
    [DllImport("DNNETestNE", CallingConvention = CallingConvention.StdCall)]
    public extern static void Test();
}

工作正常!


现在我try 将其移动到Inno设置:

[Files]
Source: Files\Dotnet\DNNETest.deps.json; Flags: dontcopy
Source: Files\Dotnet\DNNETest.dll; Flags: dontcopy
Source: Files\Dotnet\DNNETest.runtimeconfig.json; Flags: dontcopy
Source: Files\Dotnet\DNNETestNE.dll; Flags: dontcopy
procedure Test();
external 'Test@{tmp}\DNNETestNE.dll stdcall delayload';

procedure InitializeDotnet;
begin
  ExtractTemporaryFiles('{tmp}\DNNETest.deps.json');
  ExtractTemporaryFiles('{tmp}\DNNETest.dll');
  ExtractTemporaryFiles('{tmp}\DNNETest.runtimeconfig.json');
  ExtractTemporaryFiles('{tmp}\DNNETestNE.dll');
  Test();
end;

将崩溃Could not call proc

我也试过了

external 'Test@{tmp}\DNNETestNE.dll,DNNETest.dll stdcall delayload loadwithalteredsearchpath';

使用AnyCPUx86x64的组合,但没有效果

但同样的错误

我不确定我还可以try 什么,因为这些步骤在其他DllImport软件包中正常工作.

推荐答案

它不起作用,因为

编译器还使用下划线(\uu)前缀和由at符号(@)后跟参数列表中的字节数(十进制)组成的后缀修饰使用\uu stdcall调用约定的C函数.

来源:https://docs.microsoft.com/en-us/cpp/build/reference/exports?view=msvc-170

快速修复方法是在C#和Pascal定义上使用cdecl而不是stdcall

如果你真的想用stdcall,请继续阅读...


要修复它,请执行以下操作:

<DnneWindowsExportsDef>$(MSBuildProjectDirectory)\DnneWindowsExports.def</DnneWindowsExportsDef>

添加以下内容:

EXPORTS
   Test=Test

Test替换为要导出的函数


我制作了一个小的控制台应用程序,它将生成这个文件:只需添加一个对项目的引用,并用导出将typeof中的类名替换为1.

using DNNETest;
using System.Text;

var names = typeof(NativeExports).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).Select(m => m.Name).ToArray();

var output = new StringBuilder();
output.AppendLine("EXPORTS");

foreach (var name in names)
{
    output.AppendLine($"\t{name}={name}");
}

var result = output.ToString();
Console.WriteLine(result);
File.WriteAllText(@"SomeLocation\DnneWindowsExports.def", result);

我制作了以下示例来说明它的工作原理

public static class NativeExports
{
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
    public static void Test()
    {
        _ = NativeMethods.MsgBox(IntPtr.Zero, nameof(Test), "C#", 0);
    }

    [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
    public static void SendInt(int value)
    {
        _ = NativeMethods.MsgBox(IntPtr.Zero, $"{nameof(SendInt)}: {value}", "C#", 0);
    }

    [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
    public static void SendString(IntPtr value)
    {
        var message = Marshal.PtrToStringUni(value);
        _ = NativeMethods.MsgBox(IntPtr.Zero, $"{nameof(SendString)}: {message}", "C#", 0);
    }

    [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
    public static unsafe void ReturnString(IntPtr value, IntPtr* result)
    {
        var message = Marshal.PtrToStringUni(value);

        var returnString = new string(message.Reverse().ToArray());
        _ = NativeMethods.MsgBox(IntPtr.Zero, $"{nameof(ReturnString)}: {message} => {returnString}", "C#", 0);

        *result = Marshal.StringToBSTR(returnString);
    }

    [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
    public static int ReturnInt(int input)
    {
        return input;
    }

    public delegate bool ExpandConstantDelegate([MarshalAs(UnmanagedType.LPWStr)] string input, [MarshalAs(UnmanagedType.BStr)] out string output);
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
    public static void CallExpandConstantCallback(IntPtr callbackPtr)
    {
        var ExpandConstant = Marshal.GetDelegateForFunctionPointer<ExpandConstantDelegate>(callbackPtr);

        var constant = "{tmp}";
        ExpandConstant(constant, out var result);

        _ = NativeMethods.MsgBox(IntPtr.Zero, $"{nameof(ExpandConstant)}({constant}) => {result}", "C#", 0);
    }
}
procedure Test();
external 'Test@{tmp}\DNNETestNE.dll stdcall delayload';

procedure SendInt(value: Integer);
external 'SendInt@{tmp}\DNNETestNE.dll stdcall delayload';

procedure SendString(value: string);
external 'SendString@{tmp}\DNNETestNE.dll stdcall delayload';

procedure ReturnString(value: string; out outValue: WideString);
external 'ReturnString@{tmp}\DNNETestNE.dll stdcall delayload';

function ReturnInt(value: Integer) : Integer;
external 'ReturnInt@{tmp}\DNNETestNE.dll stdcall delayload';

procedure ExpandConstantWrapper(const toExpandString: string; out expandedString: WideString);
begin
  expandedString := ExpandConstant(toExpandString);
end;

procedure CallExpandConstantCallback(callback: Longword);
external 'CallExpandConstantCallback@{tmp}\DNNETestNE.dll stdcall delayload';

procedure InitializeDotnet;
var
  outString: WideString;
begin
  ExtractTemporaryFiles('{tmp}\DNNETest*');
  Test();
  SendInt(1234);
  SendString('Hello World');
  ReturnString('ReverseMe!', outString);
  MessageBox(outString, 0);
  MessageBox(IntToStr(ReturnInt(4321)), 0);
  CallExpandConstantCallback(CreateCallback(@ExpandConstantWrapper));
end;

Csharp相关问答推荐

自定义JsonEditor,用于将SON序列化为抽象类

总是丢弃返回的任务和使方法puc无效之间有区别吗?

为什么总输出就像12.3没有一分一样?

在LINQ Where子句中使用新的DateTime

Nuget包Serilog.Sinks.AwsCloudwatch引发TypeLoadExceptions,因为父类型是密封的

模型绑定RazorPage表单

默认情况下,.NET通用主机(Host.CreateDefaultBuilder)中是否包含UseConsoleLifetime?

C#方法从AJAX调用接收NULL

如何让NLog停止写入冗余信息?

什么类型的对象存储在大对象堆(LOH)中

如何将%{v_扩展}转换为%{v_扩展}>>

Azure Functions v4中的Serilog控制台主题

Blazor Server/.NET 8/在初始加载时调用异步代码是否冻结屏幕,直到第一次异步调用完成?

如何从非异步任务中正确返回TypeResult

.NET8Blazor-为什么Rapzor渲染在for循环之后显示?

C#如何获取字符串中引号之间的文本?

如何对特定异常使用Polly重试机制?

如何保存具有多个重叠图片框的图片框?

如何在C#中抽象Vector256;T<;的逻辑以支持不同的硬件配置?

将两个JSON文件与覆盖值的主文件合并