代码之家  ›  专栏  ›  技术社区  ›  marko

如何使用自定义对象从Win32 DLL调用C函数

  •  1
  • marko  · 技术社区  · 14 年前

    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);
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   Viktor Svub    14 年前


    动态 array string (回答)和 Variant 是指向“魔术”结构的指针(它们有引用计数和负偏移量上的其他数据),这些结构由编译器内部处理。


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

    我也有一些很好的使用接口的经验( IInterface IDispatch 通过 COM InterOp)直接在Delphi和C代码之间传递对象引用。 当然,您只能调用接口的方法,但是互操作层 至少处理 WideString (友好地)和 变体 (丑)给你。