Click here to Skip to main content
15,886,791 members
Articles / Desktop Programming / Win32

How to do CreateFileMapping in a C++ DLL and access it in C#, VB and C++

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
10 Mar 2009CPOL 82.9K   2.2K   57  
This is yet another example for memory mapped files. What is cool though is unlike other samples, I have a SetData(TCHAR* Key, TCHAR* value) / GetData(TCHAR* key) pattern here.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("sharedmem.dll")]
        extern static int GetRecordCount();

        [DllImport("sharedmem.dll")]
        extern static void SetValue(
            [MarshalAs(UnmanagedType.LPTStr)] string key,
            [MarshalAs(UnmanagedType.LPTStr)] string value);

        [DllImport("sharedmem.dll")]
        extern static IntPtr GetValue([MarshalAs(UnmanagedType.LPTStr)]string key);

        public Form1()
        {
            InitializeComponent();
        }

        private void UpdateRecordCount(object sender, EventArgs e)
        {
            linkLabel2.Text = "Count = " + GetRecordCount().ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Set
            SetValue(textBox1.Text, textBox2.Text);
            UpdateRecordCount(null, null);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            IntPtr intPtr = GetValue(textBox1.Text);
            textBox2.Text = Marshal.PtrToStringUni(intPtr);
            UpdateRecordCount(null, null);
        }


    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions