FoxPro和.NET COM无需注册

3
我使用Unmanaged Exports创建本机.dll,以便从 Delphi 访问 .NET 代码而无需进行 COM 注册。
例如,我有这个 .NET 程序集:
using System;
using System.Collections.Generic;
using System.Text;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;

namespace DelphiNET
{
   [ComVisible(true)]
   [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
   [Guid("ACEEED92-1A35-43fd-8FD8-9BA0F2D7AC31")]
   public interface IDotNetAdder
   {
      int Add3(int left);
   }

   [ComVisible(true)]
   [ClassInterface(ClassInterfaceType.None)]
   public class DotNetAdder : DelphiNET.IDotNetAdder
   {
      public int Add3(int left)
      {
         return left + 3;
      }
   }

   internal static class UnmanagedExports
   {
      [DllExport("createdotnetadder", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
      static void CreateDotNetAdderInstance([MarshalAs(UnmanagedType.Interface)]out IDotNetAdder instance)
      {
         instance = new DotNetAdder();
      }
   }
}

当我在Delphi中定义相同的接口时,我可以轻松使用.NET对象:

type
  IDotNetAdder = interface
  ['{ACEEED92-1A35-43fd-8FD8-9BA0F2D7AC31}']
    function Add3(left : Integer) : Integer; safecall;
  end;

procedure CreateDotNetAdder(out instance :  IDotNetAdder); stdcall;
  external 'DelphiNET' name 'createdotnetadder';

var
  adder : IDotNetAdder;
begin
  try
   CreateDotNetAdder(adder);
   Writeln('4 + 3 = ', adder.Add3(4));
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

请查看我的Delphi问题和答案以获取详细信息。

我的问题:
在FoxPro中是否可能实现这样的功能?我尝试了以下代码,但在createdotnetadder(@ldnw)行出现“数据类型不匹配”的错误:

DECLARE createdotnetadder IN DelphiNET.dll object @ ldnw
ldnw = 0
createdotnetadder(@ldnw)
loObject = SYS(3096, ldnw)
? loObject.Add3(4)

我能否像在Delphi中一样在FoxPro中定义接口?如果不能,我能否在FoxPro中使用这个.dll文件?我使用的是Visual FoxPro 9.0 SP2。谢谢。

Rick Strahl在这里有一篇关于VFP COM互操作的好文章:http://www.west-wind.com/presentations/VfpDotNetInterop/DotNetFromVFP.asp - Brian Vander Plaats
@Brian:我知道Rick的页面。我想避免COM注册,但在FoxPro中似乎不可能。 - Lukas Cenovsky
2个回答

1

很遗憾,CLR主机对我不起作用。.NET代码密集使用线程,退出foxpro应用程序时出现了Loader Lock异常。 - Lukas Cenovsky
那么,您可能希望将CLR作为进程外托管。您在问题中提到您已经让Delphi/UnmanagedExports工作了 - 它是在进程内还是进程外运行的? - Brian Vander Plaats
Delphi正在进行中,但您必须调整浮点异常处理。无论如何,我已经转向COM——虽然我担心最终用户计算机上的注册问题。 - Lukas Cenovsky
如果你遇到了加载器锁定异常,那么这是由于未释放线程所致。在关闭你的FoxPro应用程序之前,你需要确保关闭所有线程,否则VFP将在关闭时崩溃。这是标准操作,与COM互操作无关 - 在使用线程并且有未完成的线程运行的.NET或Win32应用程序中也会发生同样的情况。 - Rick Strahl

0

您还可以使用开源wwDotnetBridge项目,它可以自动化CLR运行时托管过程,并提供一系列其他支持功能,使在FoxPro中使用.NET类型和结构更加容易。

loBridge = CREATEOBJECT("wwDotnetBridge","V4")
loBridge.LoadAssembly("MyAssembly.dll")
loInstance = loBridge.CreateInstance("MyNamespace.MyClass")

loInstance.DoSomething(parm1)
loBridge.InvokeMethod(loInstance,"SomeOtherMethodWithUnsupportedTypeParms",int(10))

wwDotnetBridge会为您处理对象的创建,并返回和本地COM互操作一样的COM实例,但它还提供了通过COM互操作无法访问的其他功能:
  • 可以访问静态方法和成员
  • 可以访问值类型
  • 支持更新数组和集合
  • 支持重载的方法和构造函数
  • 可以访问泛型类型
此外,还有许多辅助工具可帮助您解决COM与.NET映射中的限制问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接