How to create and initialize SAFEARRAY of doubles in C++ to pass to C#

前端 未结 3 2015
别跟我提以往
别跟我提以往 2020-12-08 17:19

My C# method needs to be invoked from C++

Originally my C# method takes a parameter of type double[], but when calling from C++ it becomes a SAFEARRAY

In C++

3条回答
  •  失恋的感觉
    2020-12-08 17:38

    Continuing on @Liton's answer, I want to stress his last sentence, i.e. ATL's CComSafeArray. It really can save you a lot of typing. CComSafeArray has C++ constructors, destructors, operator overloads including one for [ ] that gives you an read / write reference to any element in the SAFEARRAY. In short, you can really focus on your business logic and needn't worry about the SAFEARRAY plumbing:

    #include 
    #include 
    // ...
    
        CComSafeArray arr(10);
        arr[0] = 2.0;
        arr[1] = 3.0;
        arr[2] = 5.0;
        // ...
    

    At the very least, even if you're not going to use CComSafeArray it's worthwhile to deconstruct its source code in giving you better insight on the what, when, why and how on SAFEARRAY functions.

提交回复
热议问题