Calling a DLL from CSharp -- How?

I am trying to learn to call an External DLL from a CSharp program.   I created a very simple Visual C++ CLR Class Library using the new project wizard in vs2013.   Here is its source:

// ClassLibrary1.h

#pragma once

using namespace System;

namespace ClassLibrary1 {

      public ref class Class1
            // TODO: Add your methods for this class here.


            int getint()
                  return 123;

You can see that it has one method getint() which just returns an integer value of 123.   Pretty simple.

Now I have created another project as a CSharp console app.   All I want to do is call the getint() method.  I right clicked on the project name in solution explorer, clicked add, clicked existing item and selected the DLL from the above project.
Here is the source from the c# console app.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//#include <span class="code-keyword"><vcclr.h></span>

namespace ConsoleApplication5
    class Program
        static void Main(string[] args)
            //ClassLibrary1.Class1 m = new ClassLibrary1.Class1();  // not right at all!!!!

what is the magic that I need to do in the c# console app to call getint()?  

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

This isn't terribly difficult, but there are a couple of things you have to watch out for.

Specifically a .NET 'int' is the same size as a C 'long' (.NET short = C int).   Be sure to watch your definitions.   Also, a C dll can use pointers in the parameter call - you will need to "marshal as reference".

with that, onto the heart of the discussion - how to use a .dll

1) you can add it to your project at design time, or you can look for it at runtime.  If you are going to include it at design time you simply add it to your project and then create a reference to it in your code.

  public static extern long TestFunction([MarshalAs(UnmanagedType.LPStr)] string sPointerVar, long lVar2, double dVar3, ref double dRefVar );

Open in new window

You can also use reflections and then load the assembly on the fly

Assembly assembly = Assembly.LoadFile("Absolute path to dll");
Object o = assembly.CreateInstance("dllSource.Operation");

Open in new window

roujeskyAuthor Commented:
interesting...  Looking at loading on the fly, I did this
        static void Main(string[] args)
            Assembly assembly = Assembly.LoadFile(@"D:\sc\MFCLibrary1\Debug\MFCLibrary1.dll");
            Object o = assembly.CreateInstance("MFCLibrary1.CMFCLibrary1App");    
Compiles, but I get a "BadImageFormatException was unhandled" on the LoadFile row.   I *KNOW* the dll is there.
the other question is once I have the Object o, how do i call
o.getintint() method?  Not sure I am calling CreateInstance correctly.  CMFCLibrary1App is the name of the class.  Is the call to createinstance called like dllname.classname?

I guess i need a little more hand holding....
roujeskyAuthor Commented:
I have both the dll and the application set to 64bit, so I dont think this is a 32/64bit exception....
path is not a valid assembly.
Version 2.0 or later of the common language runtime is currently loaded and path was compiled with a later version.

Open in new window


        static void Main(string[] args)
            Assembly asm = Assembly.LoadFile(@"D:\sc\MFCLibrary1\Debug\MFCLibrary1.dll");
            Object o = asm.CreateInstance("MFCLibrary1.CMFCLibrary1App");    

            Type myType = asm.GetType("MFCLibrary1.CMFCLibrary1App");
            ConstructorInfo constInfo = myType.GetConstructor(new Type[] { });

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.