新文章 网摘 文章 随笔 日记

非托管导出:在delphi中使用C#对象

更精确地遵循此处的示例(避免使用IDispatch / Dual接口),它可以正常工作:

C#

using RGiesecke.DllExport;
using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
    [ComVisible(true)]
    [Guid("8871C5E0-B296-4AB8-AEE7-F2553BACB730"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface ISample
    {
        [return: MarshalAs(UnmanagedType.BStr)]
        string GetText();
        void SetText([MarshalAs(UnmanagedType.BStr)]string value);
        [return: MarshalAs(UnmanagedType.BStr)]
        string TestMethod();
    }
    public class Sample : ISample
    {
        public string Text { get; set; }
        public string GetText()
        {
            return Text;
        }
        public void SetText(string value)
        {
            Text = value;
        }
        public string TestMethod()
        {
            return Text + "...";
        }
    }
    public static class UnmanagedExports
    {
        [DllExport(CallingConvention = CallingConvention.StdCall)]
        public static void CreateSampleInstance([MarshalAs(UnmanagedType.Interface)] out ISample instance)
        {
            instance = null;
            try
            {
                instance =  new Sample { Text = "Hello, world" };
            }
            catch
            {
            }
        }
    }
}

德尔福/拉撒路

type
  ISample = interface(IUnknown)
  ['{8871C5E0-B296-4AB8-AEE7-F2553BACB730}']
    function GetText: WideString; safecall;
    procedure SetText(const Value: WideString); safecall;
    function TestMethod: WideString; safecall;
    property Text: WideString read GetText write SetText;
  end;

procedure CreateSampleInstance(out Sample: ISample); stdcall; external 'MyLibrary.dll';

...
var
  Sample: ISample;
begin
  CreateSampleInstance(Sample);
  Writeln(Sample.Text);
  Writeln(Sample.TestMethod);
  Readln;
end;



https://stackoverflow.com/questions/49008431/unmanaged-exports-consume-c-sharp-object-in-delphi
posted @ 2021-03-10 15:00  岭南春  阅读(200)  评论(0)    收藏  举报