【问题标题】:C# program calls vc++ function which has BSTR as input parameterC#程序调用以BSTR为输入参数的vc++函数
【发布时间】:2014-06-27 15:00:55
【问题描述】:

在 C# 程序中,我正在调用以 BSTR 作为输入参数的 VC++ 函数。我没有得到任何返回值。我的 c# 应用程序崩溃了。

C#:SampleCS,

var value = object.GetValue(10, "TEST");

VC++:SampleCPP,

GetValue(long index, BSTR key, double * Value) { CString str = 键; .. .. }

知道我是否遗漏了什么或做错了什么?

注意:如果我从 VB6 调用 VC++ 的 GetValue 函数,那么它可以正常工作。

【问题讨论】:

  • 它适用于 VB6,因为 VB6 使用了不同于 .NET 字符串的 BSTR。见msdn.microsoft.com/en-us/library/windows/desktop/…
  • 是的,你是对的。但是我应该如何从 C# 传递字符串值,在传递之前我需要格式化它吗?
  • 既然 c++ 东西似乎是专门为 VB6 编写的,为什么不将 it 改为现在使用 .NET 字符串呢?见stackoverflow.com/q/2380594/1070452
  • 你能发布你的 pinvoke 声明吗?

标签: c# visual-c++ vb6 bstr


【解决方案1】:

Marshal 类具有从托管代码处理 BSTRs 的方法。试试这样的:

// Note that the BSTR parameter in C++ becomes
// an IntPtr in this PInvoke declaration.
[DllImport("your.dll")]
private void GetValue(long index, IntPtr key, ref double value);

要使用这种方法:

double result = 0;
var stringValue = "Foo";
var bstrValue = Marshal.StringToBSTR(stringValue);
try
{
    GetValue(0, bstrValue, ref result);
}
finally
{
    Marshal.FreeBSTR(bstrValue);
}

【讨论】:

  • private void GetValue(long index, [MarshalAs(UnmanagedType.BStr)]string key, ref double value); 也应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
相关资源
最近更新 更多