Hi,
I am a complete newbie and these are the first lines of code that I write, so please be patient :(
I need to create a C# exe file that calls a c++ function

What I wrote always throws an error at runtime:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at DDecrypt.DefaultDecrypt(String s)
   at DDecrypt.Main()

The function it calls is in a C++ dll ()closed source code); exploring the exposed functions I found:

1. void CLSCrypt::default constructor closure(void)
2. CLSCrypt::CLSCrypt(bool,class _bstr_t const &)
3. class _bstr_t CLSCrypt::DecryptString(class _bstr_t const &,enum STRCODING,bool)
[B]4. class _bstr_t CLSCrypt::DefaultDecrypt(class _bstr_t const &)[/B]
5. class _bstr_t CLSCrypt::DefaultEncrypt(class _bstr_t const &)
6. void CLSCrypt::Delete(void)
7. class _bstr_t CLSCrypt::EncryptString(class _bstr_t const &,enum STRCODING)
8. class _bstr_t CLSCrypt::GetBase64(unsigned char *,unsigned long)
9. bool CLSCrypt::GetFromBase64(class _bstr_t const &,unsigned char * &,unsigned long &)
10. bool CLSCrypt::GetFromHEX(class _bstr_t const &,unsigned char * &,unsigned long &)
11. class _bstr_t CLSCrypt::GetHEX(unsigned char *,unsigned long)
12. class _bstr_t CLSCrypt::GetMD5String(unsigned char *,unsigned long,enum STRCODING)
13. void CLSCrypt::SetAccess(class _bstr_t const &,unsigned long)
14. CLSCrypt::~CLSCrypt(void)

the function I want to call is

class _bstr_t CLSCrypt::DefaultDecrypt(class _bstr_t const &)

and it's mangled code is

?DefaultDecrypt@CLSCrypt@@SA?AV_bstr_t@@ABV2@@Z

to test the import of the function I wrote:

using System;
using System.Runtime.InteropServices;
public class DDecrypt
{
    [DllImport("LSUtils.dll", EntryPoint = "?DefaultDecrypt@CLSCrypt@@SA?AV_bstr_t@@ABV2@@Z", ExactSpelling = true)]
    public static extern String DefaultDecrypt(String s);
    public static void Main()
    {
        String s = "this is a test!";
        String y = DefaultDecrypt(s);
        Console.WriteLine(y);
    }
}

when I run it the error is the one above;

I suppose it is due to the data type that I want to pass (a String while the function wants something else)

I tried to import the function as

public static extern String DefaultDecrypt([MarshalAs(UnmanagedType.BStr)] String s);

or even to mark the code as 'unsafe' and use as input

IntPtr ptr = Marshal.PtrToStringBSTR(s);

but the error is always the same;

Could somebody help me with this?
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.