Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 130395
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T05:56:29+00:00 2026-05-11T05:56:29+00:00

I have a C# class library that contains methods that need to be used

  • 0

I have a C# class library that contains methods that need to be used with an external application. Unfortunately this external application only supports external APIs in C/C++.

Now I’ve managed to get a very simple COM example working between a C++ dll and a C# DLL, but I am stuck on how I can move around array data.

This is what I’ve got so far, just as a little example I found on the web of communicating via COM:

DLL_EXPORT(void) runAddTest(int add1,long *result) {     // Initialize COM.     HRESULT hr = CoInitialize(NULL);      // Create the interface pointer.     IUnitModelPtr pIUnit(__uuidof(UnitModel));      long lResult = 0;      // Call the Add method.     pIUnit->Add(5, 10, &lResult);      *result = lResult;      // Uninitialize COM.     CoUninitialize();  } 

This works fine to call the add method in my C# class. How can I modify this to take and return an array of doubles? (ill also need to do it with strings down the line).

I need to take an unmanaged array , pass this array to a C# class for some calculations, and then pass it back the results to the array reference specified in the original function call (unmanaged) C++.

I’ll need to expose a function like this:


*calcin – reference to array of doubles

*calcOut – reference to array of doubles

numIN – value of size of input array

DLL_EXPORT(void) doCalc(double *calcIn, int numIn, double *calcOut) {       //pass the calcIn array to C# class for the calcuations        //get the values back from my C# class        //put the values from the C# class        //into the array ref specified by the *calcOut reference    } 

I think I can use a C++\CLI DLL for the external application so if this is easier than straight COM then i’ll be willing to look at that.

Please be gentle as I am primarily a C# developer but have been thrown in the deep end of Interop and C++ .

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T05:56:29+00:00Added an answer on May 11, 2026 at 5:56 am

    I experimented with this a while ago but have unfortunately forgotten how it all fitted together… for my purpose it turned out to be woefully slow so I cut out the C# and went back to all C++. When you say you’re primarily a C# developer I hope you understand pointers because if you don’t there’s no way to be gentle.

    Passing arrays basically came down to using CoTaskMemAlloc family of functions on the C++ side (http://msdn.microsoft.com/en-us/library/ms692727(VS.85).aspx) and the Marshal class on the C# side (http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx – which has methods like AllocCoTaskMem). For C# I ended up with a utility class:

    public class serviceUtils {     unsafe public long stringToCoTaskPtr( ref str thestring )     {         return (long)Marshal.StringToCoTaskMemAnsi(thestring.theString).ToPointer();//TODO : what errors occur from here? handle them     }      unsafe public long bytesToCoTaskPtr( ref bytes thebytes, ref short byteCnt)     {         byteCnt = (short)thebytes.theArray.Length;         IntPtr tmpptr = new IntPtr();         tmpptr = Marshal.AllocCoTaskMem(byteCnt);         Marshal.Copy(thebytes.theArray, 0, tmpptr, byteCnt);         return (long)tmpptr.ToPointer();     }      public void freeCoTaskMemPtr(long ptr)     {         Marshal.FreeCoTaskMem(new IntPtr(ptr));//TODO : errors from here?     }      public string coTaskPtrToString(long theptr)     {         return Marshal.PtrToStringAnsi(new IntPtr(theptr));     }      public byte[] coTaskPtrToBytes(long theptr, short thelen)     {         byte[] tmpbytes = new byte[thelen];         Marshal.Copy(new IntPtr(theptr), tmpbytes, 0, thelen);         return tmpbytes;     } } 

    Just to throw some more code at you: this c++

    #import '..\COMClient\bin\Debug\COMClient.tlb' named_guids raw_interfaces_only int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(NULL);   //Initialize all COM Components COMClient::IComCalculatorPtr pCalc; // CreateInstance parameters HRESULT hRes = pCalc.CreateInstance(COMClient::CLSID_ComCalculator); if (hRes == S_OK) {     long size = 5;     LPVOID ptr = CoTaskMemAlloc( size );     if( ptr != NULL )     {         memcpy( ptr, '12345', size );         short ans = 0;         pCalc->changeBytes( (__int64*)&ptr, &size, &ans );         CoTaskMemFree(ptr);     } }  CoUninitialize ();   //DeInitialize all COM Components  return 0; } 

    called this c#

        public short changeBytes(ref long ptr, ref int arraysize)     {         try         {             IntPtr interopPtr = new IntPtr(ptr);                             testservice.ByteArray bytes = new testservice.ByteArray();             byte[] somebytes = new byte[arraysize];             Marshal.Copy(interopPtr, somebytes, 0, arraysize);             bytes.theArray = somebytes;              CalculatorClient client = generateClient();             client.takeArray(ref bytes);             client.Close();             if (arraysize < bytes.theArray.Length)             {                 interopPtr = Marshal.ReAllocCoTaskMem(interopPtr, bytes.theArray.Length);//TODO : throws an exception if fails... deal with it             }             Marshal.Copy(bytes.theArray, 0, interopPtr, bytes.theArray.Length);             ptr = interopPtr.ToInt64();              arraysize = bytes.theArray.Length;              //TODO : do we need to free IntPtr? check all code for memory leaks... check for successful allocation         }         catch(Exception e)         {             return 3;         }          return 2;     } 

    Sorry, but I don’t have the time to work all this out and explain it properly, hopefully this will give you pointers in the right direction, at the very least some things to google. Good Luck

    PS : I got all the info to write this stuff off the net, so it is out there.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 122k
  • Answers 122k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You should write : if (self.a != 0) and (self.b… May 12, 2026 at 12:36 am
  • Editorial Team
    Editorial Team added an answer If you care about order, then just use the equals… May 12, 2026 at 12:36 am
  • Editorial Team
    Editorial Team added an answer I'm not an Eclipse expert, but since you didn't get… May 12, 2026 at 12:36 am

Related Questions

I am having a couple of issues deciding how best to describe a certain
We have a database library in C# that we can use like this: DatabaseConnection
I have an associative array (object) of the following construction var menu = new

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.