Stefan
Stefan

Reputation: 3869

How do I call a C++ DLL from C#/WPF project

I have the below code:

namespace WPFMuskTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport
            ("myDll.DLL", 
             EntryPoint = "?Func1@FUllNameCopiedFromDependancyWalker",
             CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl
            )
        ]
        public static extern System.IntPtr Func1(out System.IntPtr handle, int type, out  DateTime date);

        public MainWindow()
        {
            InitializeComponent();
            //
            // 
            // 
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            System.IntPtr MainParam;
            int thetype = 1
            DateTime date;

            System.IntPtr res = GetFxIRMoveForDate(out MainParam, thetype _til, out date);
        }
    }
}

The exe is in the same path as the called DLL and the function definitely exists in the DLL (verified in DependacyWalker) but I keep getting the error:

The function prototype being called is:

class __declspec(dllexport) OUR_DATE_TYPE { .... }

typedef unsigned long TYPE; typedef DATE_TYPE OUR_DATE_TYPE;

namespace1
{
namespace2
{
void func1(MyClass &myclass, const TYPE& type, const DATE_TYPE& date);
}
}

An unhandled exception of type 'System.AccessViolationException'

Can anyone tell me why?

Upvotes: 1

Views: 1557

Answers (1)

Dan
Dan

Reputation: 13210

By default, c++ does not use the cdecl calling convention, it uses stdcall. You would probably have more success writing a c wrapper to the c++ api and calling that instead, because C has a well-defined ABI.

EDIT: looking at your code again, I doubt DateTime is the same as the date type you're using in C++. If it's the wrong size, for example, this error could occur.

Upvotes: 1

Related Questions