I am having trouble figuring out how to pass a buffer address from C# to C. I have checked several references. One seems to explain how (passing pointers referencing memory allocated in managed code to unmanaged) but when I mimic it I can't get it to work.
The output should be "This is data" but what comes out is "buffer=System.Char[]".
If I use the debugger I can see that the string "This is data" is in fact being copied properly but the address of 'buffer' in the C function is different than the address of 'buffer' in the C# code. So I'm thinking the referenced link above is assuming some other knowledge of C# which is not explained. Or maybe I just don't understand the additional answers.
Here is my code:
XBaseNamespace.cs
-----------------
// XBase functions
using System;
using System.Runtime.InteropServices;
namespace XBaseNamespace.SecondNamespace
{
class XBaseFunctions
{
[DllImport("W:\\C_sharp\\Call_C\\Debug\\C_dll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern void ProcessBigBuffer([MarshalAs(UnmanagedType.LPArray)] char[] buffer);
}
}
Program.cs
----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using XBaseNamespace.SecondNamespace;
namespace Call_C
{
class Program
{
static void Main()
{
char[] buffer = new char[1000];
// initialize the buffer
// and then process it
XBaseFunctions.ProcessBigBuffer(buffer);
Console.WriteLine("buffer={0}\n", buffer);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
c_dll.c
-------
// C DLL experiment
#include <stdio.h>
#include <string.h>
#define DSI_DLL __declspec(dllexport)
#define CALL_TYPE //__stdcall
DSI_DLL void CALL_TYPE ProcessBigBuffer( char* buffer )
{
strcpy( buffer, "This is data" );
}