Jump to content
  • Advertisement
Sign in to follow this  
AntonyCoder

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

This topic is 4590 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
		
	}
	
}

Share this post


Link to post
Share on other sites
Advertisement
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 code

System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!