[英]C++ Calling Function from C# COM DLL
I'm trying to call a string function from a C# DLL that I made (to test COM out). 我正在尝试从我制作的C#DLL中调用字符串函数(以测试COM)。 I have a function called
add
which takes two int
s and returns the sum. 我有一个名为
add
的函数,该函数接受两个int
并返回总和。 This seems to work. 这似乎有效。 My other function,
returnString
, takes a string and returns it. 我的另一个函数
returnString
接受一个字符串并将其返回。 This ends up printing out something blank. 最终打印出空白。 Here is the code:
这是代码:
C#: C#:
public class Class1 : MyClass
{
public string returnString(string a)
{
return a;
}
public int add(int a, int b)
{
return a + b;
}
}
C++: C ++:
int main()
{
CoInitialize(NULL);
MyClassPtr obj;
obj.CreateInstance(__uuidof(Class1));
BSTR string_result = L"\0";
int int_result = 0;
HRESULT hr1 = obj->returnString(L"Hello", &string_result); // should set string_result to "Hello"
HRESULT hr2 = obj->add(5, 7, (long*)&int_result); // should set int_result to 12
if (hr1 != S_OK)
std::cout << "hr1: " << hr1 << std::endl;
else{
_bstr_t str(string_result);
std::cout << str << std::endl; // prints a blank line rather than "Hello"
}
if (hr2 != S_OK)
std::cout << "hr2: " << hr2 << std::endl;
else
std::cout << int_result << std::endl; // prints 12
CoUninitialize();
}
Here's what I get when I peak the definitions: 当我达到定义的峰值时,这就是我得到的:
virtual HRESULT __stdcall returnString (
/*[in]*/ BSTR a,
/*[out,retval]*/ BSTR * pRetVal ) = 0;
virtual HRESULT __stdcall add (
/*[in]*/ long a,
/*[in]*/ long b,
/*[out,retval]*/ long * pRetVal ) = 0;
So what's wrong with the code? 那么代码有什么问题呢? I posted a similar question recently and found out a little bit more, but I still cannot get it to behave properly.
我最近发布了一个类似的问题,发现了更多问题,但仍然无法使其正常运行。 Thank you!
谢谢!
Here was the problem: L"Hello"
needed to be casted to type CComBSTR
. 这就是问题所在:需要将
L"Hello"
强制转换为CComBSTR
类型。 This is what the result should look like: 结果如下所示:
HRESULT hr1 = obj->returnString((CComBSTR)L"Hello", &string_result);
Everything else can remain the same :) 其他一切都可以保持不变:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.