[.net] How do you pass a string to a C++ DLLIMPORT-ed function(Const char *)?

Started by
2 comments, last by RipTorn 18 years ago
I've wrote several functions in C++ that take const char * strings as parameters, but I can't seem to find any match in C# (Mono latest windows version) that doesn't throw an exception saying there was an attempt to read protected memory. Here's the test dll function I wrote,

DLL const char * _stdcall TestString(const char *buf)
{
    LogManager::getSingleton().logMessage("Test String Called.");
    LogManager::getSingleton().logMessage( buf );
    return "Testing String.";
}

And here's the C# source that invokes the function. I tried regular C# strings first, then based on a tutorial I tried StringBuilder, both to no avail.


using System;
using System.Text;
using System.Runtime.InteropServices;

namespace AuroraC
{
	class Program
	{
		static void Main(string[] args)
		{
			StringBuilder b=new StringBuilder(100);
			b.Append("Test 1");
			Console.WriteLine("Hello world!");
			Console.WriteLine("hello word");
			DLL.TestString( b );
		}
	}
	
	class DLL
	{
		[DllImport("OgreMax.dll", EntryPoint="_InitOgre@0",
				   ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
		public static extern void InitOgre();
		[DllImport("OgreMax.dll", EntryPoint="_InitOgre2@0",
				   ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
		public static extern void InitOgre2();
		[DllImport("OgreMax.dll", EntryPoint="_TestString@4",
				   ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
		public static extern StringBuilder TestString(StringBuilder str);
		
	}
	
}

Advertisement
Try to use a system string instead of StringBuilder.

HTH,
Pat.
I tried and it failed with the same error.

Is there no way of converting a string into a byte ptr I can pass to the function?
there is more than one way, here is one:

IntPtr ptr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi("omg, wtf, bbq");... use the pointer in your unmanaged codeSystem.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);

This topic is closed to new replies.

Advertisement