0

I was just following msdn docs to understand the native c++ dynamic libraries implementation for C# projects. So I started with fresh visual studio sln as follows:

==> C++ dll console application which contains test header and definitions

Test.h

#ifdef  TESTFUNCDLL_EXPORT
#define TESTFUNCDLL_API __declspec(dllexport)
#else
#define TESTFUNCDLL_API __declspec(dllimport)
#endif //  TESTFUNCDLL_EXPORT

#include <string>


extern "C" {
    TESTFUNCDLL_API float TestMultiply(float a, float b);
    TESTFUNCDLL_API std::string CPPOwnerName(int ind);
    TESTFUNCDLL_API int GetIntCPP();
    TESTFUNCDLL_API int DoubleIntCPP(int num);
}

Test.cpp

#include "Test.h"

extern "C" {

    float TestMultiply(float a, float b)
    {
        return a*b;
    }

    std::string CPPOwnerName(int ind)
    {
        return "Shubham Singh. CPP!";
    }

    int GetIntCPP()
    {
        return 3;
    }

    int DoubleIntCPP(int num)
    {
        return 2 * num;
    }
}

==> C# class library

TestClass.cs

using System.Runtime.InteropServices;

namespace CSharpLibrary
{
    public class TestCS
    {
        [DllImport("CPPLibrary")]
        public static extern float TestMultiply(float a, float b);

        [DllImport("CPPLibrary")]
        public static extern string CPPOwnerName(int ind);

        [DllImport("CPPLibrary")]
        public static extern int GetInt();

        [DllImport("CPPLibrary")]
        public static extern int DoubleIntCPP(int num);

        public static float SharpMultiply(float a, float b)
        {
            return a * b;
        }

        public static string CSharpOwnerName()
        {
            return "Shubham Singh. C#";
        }

        public static int GetInteger()
        {
            return 2;
        }
    }
}

Now after importing both the libraries in my current C# project. I am unable to access few CPP library functions like: CPPOwnerNAme(string) or GetIntCPP() but on contrary I am able to access other two functions: TestMultiply(float,float) and DoubleIntCPP(int)

Earlier I thought the extern functions need to have parameters for them to be accessible as I was getting EntryPointNotFound Exception for CPPOwnerName() but after including parameter "ind" the program is just simple crashing!!!

Any sort of help/guide is appreciated. Thanks.

enigma
  • 113
  • 8
  • @UnholySheep thank you for pointing to right thread. In my case it was a combination of both: typo and unawareness that you can't pass up the string. – enigma Mar 26 '18 at 16:46
  • @unholySheep on the same note, can you tell if I can use any of the user define data types such as struct, lists or other containers for returning the value? – enigma Mar 26 '18 at 16:52

0 Answers0