代码之家  ›  专栏  ›  技术社区  ›  sergiom

引脚阵列

  •  0
  • sergiom  · 技术社区  · 15 年前

    我需要封送一个字符串^数组来调用需要一个BSTR数组的非托管函数。

    我在MSDN上找到了那篇文章

    How to: Marshal COM Strings Using C++ Interop

    使用此代码示例:

    // MarshalBSTR1.cpp
    // compile with: /clr
    #define WINVER 0x0502
    #define _AFXDLL
    #include <afxwin.h>
    
    #include <iostream>
    using namespace std;
    
    using namespace System;
    using namespace System::Runtime::InteropServices;
    
    #pragma unmanaged
    
    void NativeTakesAString(BSTR bstr) {
       printf_s("%S", bstr);
    }
    
    #pragma managed
    
    int main() {
       String^ s = "test string";
    
       IntPtr ip = Marshal::StringToBSTR(s);
       BSTR bs = static_cast<BSTR>(ip.ToPointer());
       pin_ptr<BSTR> b = &bs;
    
       NativeTakesAString( bs );
       Marshal::FreeBSTR(ip);
    }
    

    因此,我创建了一个新的BSTRs数组,并为数组中的每个字符串调用Marshal::StringToBSTR()。 然后我创建了一个托管的pin\u ptr数组。

    array<pin_ptr<BSTR> >^ gcDummyParameters = gcnew array<pin_ptr<BSTR> >(asParameters->Length);
    

    Error   2   error C2691: 'cli::pin_ptr<Type>' : a managed array cannot have this element type
    

    我还尝试使用本机数组:

    pin_ptr<BSTR> dummyParameters[100000];
    

    但即使在这种情况下,我也犯了一个错误:

    Error   1   error C2728: 'cli::pin_ptr<Type>' : a native array cannot contain this managed type 
    

    我还能做什么?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Alex F    15 年前

    Microsoft示例看起来很奇怪:没有必要固定BSTR类型,因为它是非托管的。只需创建BSTR数组并使用Marshal::StringToBSTR填充每个成员。不要使用密码。

        2
  •  2
  •   Ben Voigt    15 年前

    针ptr应从该样品中移除。bs是一个局部变量,垃圾收集器不会移动它,它也会通过值传递给本机函数,因此如果它确实移动了,就不会有问题。

    它指向的BSTR内容是由系统的BSTR分配器本机分配的,垃圾收集器也不会移动它。

    推荐文章