How to use Pchar function to use C #

How can I use this feature in C #?

function CheckCard (pPortID:LongInt;pReaderID:LongInt;pTimeout:LongInt): PChar;

      

This feature included dll.

I can try:

[DllImport("..\\RFID_107_485.dll", CharSet = CharSet.Auto, 
    CallingConvention = CallingConvention.ThisCall)]
public static extern char CheckCard(int pccPortID, int pccdReaderID, int pccTimeout);
                     char pccCheckCard = CheckCard(3, 129, 1000);
                     Console.WriteLine(pccCheckCard);

      

but I am not getting a true answer ...

Please help me?:)

+3


source to share


1 answer


There are many problems here. This is what I see:

  • The Delphi code as written uses the Delphi calling convention register

    . This is only available from Delphi code and cannot be called by the p / invoke method. However, it is possible that you excluded the calling code from the code, and in fact it is stdcall

    .
  • Your p / invoke is used CallingConvention.ThisCall

    which certainly doesn't match any Delphi feature. This calling convention is not supported by Delphi.
  • You mistranslate PChar

    , a pointer to an array of nullable characters char

    , one UTF-16 character.
  • Delphi code looks suspicious. The function returns PChar

    . Well, who is responsible for freeing the returned string. I wouldn't be surprised if Delphi code returned a pointer to a string variable that gets destroyed when the function returns, a very common mistake.
  • You are referencing the DLL using a relative path. This is very risky because you cannot easily control whether the DLL is found. Place the DLL in the same directory as the executable and provide only the name of the DLL file.
  • No error checking is observed.

A variant that might work might look like this:

Delphi



function CheckCard(pPortID: LongInt; pReaderID: LongInt; pTimeout: LongInt): PChar; 
    stdcall;

      

FROM#

[DllImport("RFID_107_485.dll", CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr CheckCard(int pccPortID, int pccdReaderID, int pccTimeout);
....
IntPtr pccCheckCard = CheckCard(3, 129, 1000);
// check pccCheckCard for errors, presumably IntPtr.Zero indicates an error

// assuming ANSI text
string strCheckCard = Marshal.PtrToStringAnsi(pccCheckCard);
// or if the Delphi code returns UTF-16 text      
string strCheckCard = Marshal.PtrToStringUni(pccCheckCard);

      

This leaves the question of how to free the returned pointer unresolved. You will need to consult your documentation to find this feature. The question contains insufficient information.

+1


source







All Articles