我正在尝试在一个非托管的Visual C++解决方案中调用来自C# COM项目的方法,但是我一直遇到下面的错误:
First-chance exception at 0x7697C41F (KernelBase.dll) in Program.exe: 0x04242420 (parameters: 0x31415927, 0x6F310000, 0x00BBDAE8).
在下面的代码片段中,
SalesForceNew::IMyObjectClassPtr p;
p.CreateInstance(__uuidof(SalesForceNew::TestObject)); // error
SalesForceNew::MyObject mo = p->getObject(1, "a");
然而mo
的值与预期相符合(5, "aa")。
我使用以下代码导入tlb文件:
#import "C:\Users\Bob\Desktop\ComTest\SalesForceNew\bin\x86\Debug\SalesForceNew.tlb" named_guids
以下是 C# 项目:
接口:
using System.Runtime.InteropServices;
namespace SalesForceNew
{
[ComVisible(true)]
[Guid("22901ACD-CA30-4D3E-B84B-73B707026AE5")]
public interface IMyObjectClass
{
MyObject getObject(int i, string s);
}
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential)]
public struct MyObject
{
public int Getal;
public string Text;
}
}
实现接口的类:
using System.Runtime.InteropServices;
namespace SalesForceNew
{
[ClassInterface(ClassInterfaceType.None)]
[Guid("234A2A35-F270-458D-A67B-C834EB794B27")]
[ComVisible(true)]
public class TestObject : IMyObjectClass
{
public MyObject getObject(int i, string s)
{
return new MyObject() { Getal = i * 5, Text = s + s };
}
}
}
我在 C# COM 项目的属性中勾选了
注册 COM 互操作
和 使程序集对 COM 可见
选项。
更新:如果将 C# COM 项目的框架版本更改为 2.0、3.0 或 3.5,该错误就不会出现。它只在框架版本为 4.0 或 4.5 时显示。