【问题标题】:How to call in C# function from Win32 DLL with custom objects如何使用自定义对象从 Win32 DLL 调用 C# 函数
【发布时间】:2010-05-28 12:28:36
【问题描述】:

如何在Delphi制作的Win32 DLL文件中使用C#函数。什么时候函数参数是自定义的delphi对象?

Delphi 中的函数定义:

function GetAttrbControls(    Code     : PChar;
                              InputList: TItemList;
                              var Values   : TValArray): Boolean; stdcall; export;

使用的类型:

type
  TItem = packed record
    Code : PChar;
    ItemValue: Variant;
  end;

TItemList = array of TItem;

TValArray = array of PChar;

C# 中的示例(不起作用):

[StructLayout(LayoutKind.Sequential)]
 public class Input
 {
     public string Code;
     public object ItemValue;
 };


[DllImport("Filename.dll", EntryPoint = "GetValues", CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern bool GetValues(string Code, Input[] InputList, ref StringBuilder[] Values);

【问题讨论】:

    标签: c# .net delphi winapi


    【解决方案1】:

    这不能按照你的方式完成,但你还有一些可能性。

    Dynamic array (declared w/o []), string (AnsiString) 和 Variant 是指向“神奇”结构的指针(它们具有负偏移的引用计数和其他数据),由编译器内在。

    如果您真的想使用这些类型,则需要围绕接口对它们进行序列化和具体化(使用一些二进制转储格式、JSON 等)。

    您可以尝试使用任何基本类型(例如,array[]ShortStringrecord),它们将完全按照您的预期工作(注意基于 ShortString 1 的索引,长度存储为 0)使用 StructLayout,除非您将它们与托管类型混合使用。

    此外,我在使用接口(@98​​7654328@/IDispatch 通过COM InterOp)在 Delphi 和 C# 代码之间直接传递对象引用方面也有一些很好的经验。 当然,您只能调用接口的方法,但互操作层可以处理至少WideString(很好)和一些Variant(丑) 为你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多