By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,156 Members | 1,017 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,156 IT Pros & Developers. It's quick & easy.

My way of access C++ MFC code from C# Web App or Win form using a DLL

P: n/a
Hi, I thought I'd post my notes on how I went about accessing MFC C++
code in my web app after spending a day or more gathering information
on how to do it.
Please, let me know if you have a better way (especially with passing
strings into the DLL and getting strings back out), but I've found this
way is pretty simple!

Create a C++ MFC DLL project
1. expose methods to call like this in the main header, e.g.:
extern "C" __declspec(dllexport) int SomeFunction();
extern "C" __declspec(dllexport) char HelloWorld(char inputStr[1024]);
2. in the main cpp file, create the methods like this:
extern "C" __declspec(dllexport) int SomeFunction()
{
return 6;
}

extern "C" __declspec(dllexport) char HelloWorld(char inputStr[1024])
{
return inputStr[0];
}

3. compile up, and put into windows\system32 if you want it to be
accessible from ASP.Net web apps, OR if you use the LoadLibrary
technique (discussed below) you can place it where you want.
4. Make any folders (like ones that contain log file that need to be
written to by the MFC DLL) writable by the <computerName>\ASPNET user.

Create a c# Web App
1. Add the following "using": using System.Runtime.InteropServices;
2. Access the Dll using the DllImport command inside your class
definition, e.g.:
[DllImport("mfcdll.dll")]
public static extern char HelloWorld(string t);
[DllImport("mfcdll.dll")]
public static extern int SomeFunction();
3. Invoke methods on the dll as you would any method, e.g. in your
Page_Load:
int result = SomeFunction();
char result2 = HelloWorld("Tony");

If you need to access the DLL from a place other than windows\system32
1. Use Load Library to specify the dll path, by putting in the
following DllImport inside your class definition:
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
2. and before you call invoke DLL methods, invoke the LoadLibrary
method like this:
3. LoadLibrary(@"c:\MyPath\mfcdll.dll");

I hope this saves someone some time!
Cheers,
Tony.

Jun 13 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.