Gilyu
Gilyu

Reputation: 3

SEHException with simple DLL

I am currently trying to use a simple C++ DLL in a C# program for a school project but I have trouble making the DLL and Program link with each other. When I try to call the DLL's function in the main program, I get a SEHExcpetion thrown from the DLL.

Here is the DLL code

#include <stdio.h>
#include <string>

using namespace std;

extern "C"
{
    __declspec(dllexport) string Crypter(string sIn)
    {
        return sIn+ " from DLL";
    }
}  

And here's the C# code

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("CryptoDLL2.dll")]
        public static extern string Crypter(string sIn);

        public Form1()
        {
            InitializeComponent();
        }

        private void BTN_Crypter_Click(object sender, EventArgs e)
        {
            TB_OUT.Text = ("");
            TB_OUT.Text = Crypter(TB_IN.Text); //exception thrown here
        }
    }
}

Upvotes: 0

Views: 1227

Answers (3)

devshorts
devshorts

Reputation: 8872

I did a test to make sure the linking was fine, here is a sample app showing it does work.

#include <stdio.h>
#include <string>

using namespace std;

extern "C"
{
    __declspec(dllexport) string Crypter(string sIn)
    {
        printf("test");
        return "from DLL";
    }
}  

And

public class Test
{
    [DllImport("TestDll.dll")]
    public static extern string Crypter(string sIn);

    static void Main(string[] args)
    {
        Console.WriteLine(Crypter("a"));
    }
}

This prints me out

test

followed by a newline.

You need to probably marshal the data from c++ to .net, or use a c++/clr managed dll which would make things easier on you.

Upvotes: 0

Erti-Chris Eelmaa
Erti-Chris Eelmaa

Reputation: 26268

Strings in C# and C++ - Those are completely different types, layouts, etc. And you expect them to work.

Check out char* with marshalling.

Upvotes: 2

TCS
TCS

Reputation: 5900

you cannot use std::string from C#, it is a c++ class, .NET does not know how to handle it.

Try using wchar_t* or BSTR.

Upvotes: 0

Related Questions