Reputation: 1049
I have 2 applications, 1 is C++ and one is C# made. The following is my structure inside C++:
struct INFO
{
char Name[MAX_PATH];
int Number;
};
The following is my attempt to replicate the structure in C#:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct INFO
{
public byte Name;
public int Number;
}
The C++ Program ( ready to compile and test ):
#include <stdio.h>
#include <tchar.h>
#include <iostream>
using namespace std;
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT _WIN32_WINNT_WINXP
// System Include
#include <windows.h>
#include <winsock2.h>
struct INFO
{
char Name[MAX_PATH];
int Number;
};
HANDLE FileMappingHandle;
INFO* FileMapping;
void EntryProc()
{
if ((FileMappingHandle = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, sizeof(INFO), "Local\\INFO_MAPPING")) == 0)
{
return;
}
if ((FileMapping = (INFO*)MapViewOfFile(FileMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(INFO))) == 0)
{
return;
}
strcpy(FileMapping->Name, "DARKVADER");
FileMapping->Number = 1337;
printf("FileMapping->Name: %s", FileMapping->Name);
printf("FileMapping->Number: %d", FileMapping->Number);
}
int main()
{
EntryProc();
do {
cout << '\n' << "Press the Enter key to continue.";
} while (cin.get() != '\n');
return 0;
}
The C# Program ( ready to compile and test ):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO.MemoryMappedFiles;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.DoMap();
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct INFO
{
public byte Name;
public int Number;
}
public void DoMap()
{
MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity();
CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
//access memory mapped file (need persistence)
using (var memMapFile = MemoryMappedFile.CreateOrOpen("Local\\INFO_MAPPING", 1024, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable))
{
using (var accessor = memMapFile.CreateViewAccessor())
{
INFO data;
accessor.Read<INFO>(0, out data);
Console.WriteLine(data.Name);
Console.WriteLine(data.Number);
}
}
}
}
}
The Problem:
I can share numbers between the two applications using the above code, but I cannot share strings.
When I say "cannot" share, what I actually means is that instead of the actual "characters" I always get wierd chinese symbols, and even the number dissapears.
I have tried all the combinations I could think of ( byte[], string, unsafe struct, etc), in the C# struct but I have failed.
Please show me / explain to me how can I share properly strings between my 2 applications.
Example working code would be appreciated.
Upvotes: 2
Views: 8427
Reputation: 20295
To share strings you need to map them properly: https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-strings
Probably, you need to decorate (ByValTStr
uses CharSet
from your StructLayout
, so it's ANSI):
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
string Name;
EDIT: Checked on .net core. It's not allowed to use reference types in Accessor. The easiest option would be reading the array and extracting values.
var buffer = new byte[264];
accessor.ReadArray(0, buffer, 0, buffer.Length);
var endIndex = Array.FindIndex(buffer, 0, 260, x => x == 0);
var name = Encoding.ASCII.GetString(buffer, 0, endIndex == -1 ? 260 : endIndex);
var number = BitConverter.ToInt32(buffer, 260);
Another one is using unsafe:
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public unsafe struct INFO
{
[FieldOffset(0)]
public fixed byte Name[260];
[FieldOffset(260)]
public int Number;
}
class Program
{
static void Main(string[] args)
{
//CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
//access memory mapped file (need persistence)
using (var memMapFile = MemoryMappedFile.CreateOrOpen(
"Local\\INFO_MAPPING",
1024,
MemoryMappedFileAccess.ReadWriteExecute,
MemoryMappedFileOptions.None,
System.IO.HandleInheritability.Inheritable))
{
using (var accessor = memMapFile.CreateViewAccessor())
{
accessor.Read<INFO>(0, out INFO data);
string name;
unsafe
{
name = new String((sbyte*)data.Name, 0, 260);
}
Console.WriteLine(name);
Console.WriteLine(data.Number);
}
}
}
Upvotes: 4