0

I'm writing a c# console application that uses a C++ class library. In C++ language class library I have a method:

public:bool GetMDC(char fileName[], char mdcStrOut[]){
    // My Code goes Here
}

This method gets a file path in fileName parameter and puts a value in mdcStrOut.

I add this class library as reference to my C# console application. when I want to call GetMDC method the method needs two sbyte parameters. So it's signature in c# is GetMDC(sbyte* fileName, sbyte* mdcStrOut).

My code looks like this:

unsafe{
    byte[] bytes = Encoding.ASCII.GetBytes(fileName);
    var _mdc = new TelsaMDC.TelsaMDCDetection();
    var outPut = new sbyte();
    fixed (byte* p = bytes)
    {
        var sp = (sbyte*)p;
        //SP is now what you want
        _mdc.GetMDC(sp, &outPut);
    }
}

It works without error. But the problem is that outPut variable only contains the first character of mdcStrOut. I'm unfamiliar with C++. I know that I'm passing the memory address of output to the GetMDC. So how can I get the value of it in my console application?

EDIT

when I declare output variable like this var outPut = new sbyte[MaxLength] I get an error on _mdc.GetMDC(sp, &outPut); line on the & sign. It says: Cannot take the address of, get the size of, or declare a pointer to a managed type ('sbyte[]')

1 Answer 1

1

The variable outPut is a single byte. You need to create a receive buffer, for example, var outPut = new sbyte[MaxLength].

unsafe{
    byte[] bytes = Encoding.ASCII.GetBytes(fileName);
    var _mdc = new TelsaMDC.TelsaMDCDetection();
    var outPut = new sbyte[256];  // Bad practice. Avoid using this!
    fixed (byte* p = bytes, p2 = outPut)
    {
        var sp = (sbyte*)p;
        var sp2 = (sbyte*)p2;
        //SP is now what you want
        _mdc.GetMDC(sp, sp2);
    }
}

Also, I recommend to rewrite the code to avoid possible buffer overflow because the function GetMDC does not know the size of the buffer.

Sign up to request clarification or add additional context in comments.

1 Comment

Just do it the same way as the first parameter bytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.