【发布时间】:2016-03-18 12:03:01
【问题描述】:
我正在尝试将 C# dll 库包含到本机 C++ 控制台应用程序中。我正在使用这篇文章: https://support.microsoft.com/en-us/kb/828736#bookmark-7
但是这篇文章是为 Visual Studio 2015 编写的,而我使用的是 Visual Studio 2015。
首先我在 Stackoverflow 上检查了几个答案,但这些问题都不是我想要的。
最接近我的问题在这里: C# library to native C++ application
所以,我创建了一个 C# 库项目,其中包含以下代码:
namespace Testing_Library
{
// Interface declaration
public interface iCalculator
{
int Add(int number1, int number2);
}
public class ManagedClass:iCalculator
{
public int Add(int number1, int number2)
{
return number1 + number2;
}
}
}
然后我将项目编译为dll文件,然后我通过RegAsm.exe注册了dll文件。现在我有两个输出文件:
Testing_Library.dll
和
Testing_Library.tlb
我还创建了本机 C++ Windows 控制台应用程序项目。在这个项目中,我有一个带有以下代码的 .cpp 文件:
// Import the type library.
#import "..\Testing_Library\bin\Debug\Testing_Library.tlb" raw_interfaces_only
using namespace std;
using namespace Testing_Library;
void main()
{
// Initialize COM.
HRESULT hr = CoInitialize(NULL);
// Create the interface pointer.
iCalculatorPtr pICalc(__uuidof(ManagedClass));
long lResult = 0;
// Call the Add method.
pICalc->Add(5, 10, &lResult);
wprintf(L"The result is %d", lResult);
// Uninitialize COM.
CoUninitialize();
}
当我尝试运行该项目时,我收到以下错误屏幕:
目前我不知道为什么我会收到此错误 Windows 并且我无法在 Internet 上找到信息。请你帮助我好吗? 在这里您可以找到所有项目的完整解决方案: Onedrive folder
我目前正在尝试编译和运行:
Test_me
和
Testing_Library
【问题讨论】:
-
不能调试应用吗?
-
我可以,但是我是 C# 和 COM 的新手,我目前正在尝试学习它们,我不会在那里找到很多有用的信息,至少对我来说是这样。 CoInitialize 将 S_OK 返回到 HRESULT,这没问题,然后应用程序在接口指针上崩溃。最后一个屏幕给了我这个: pICalc.m_pInterface was nullptr 我还可以在微软论坛上找到这个:这是#import生成的代码的标准行为。每当接口方法返回失败 HRESULT 时,它都会将错误转换为异常。但就我而言,结果还可以
-
这一行执行后会发生什么?
iCalculatorPtr pICalc(__uuidof(ManagedClass));你有实例吗?我不是 C++ 专家,但它看起来好像和 C# 的空引用异常的等价物正在发生。例如。 pICalc 为空 -
什么都没有发生,因为程序在该行发生异常,并且无法创建接口指针。也许我需要了解为什么程序无法创建指向 iCalculator 类的指针。
-
这样的代码只有在你一切正确的情况下才有效,错误处理在 COM 代码中永远不是可选的。就像你不能忽略 Add() 的返回值一样。如果您不知道如何单步执行 iCalculatorPtr 构造函数,则使用 try { } catch (_com_error &ex) { ... } 包装此代码,以便您可以诊断 ex。并且确实在文档上花费最少的时间,试错编码有很多错误,我们的试验。
标签: c# c++ .net visual-studio visual-studio-2015