2

I'm using an NIDAQmx DLL in a Delphi XE4 app. The DLL only has an ANSI C header file.

I'm trying to convert this function:

int32 __CFUNC DAQmxGetPhysicalChanName(TaskHandle taskHandle, 
        const char channel[], char *data, uInt32 bufferSize);

This is my translation:

function DAQmxGetPhysicalChanName(taskHandle: TTaskHandle;
        chanName: PAnsiChar; chanPhysName: PAnsiChar;
        bufferSize: DWORD): Integer; stdcall; external NI_DLL_NAME delayed;

When I call it like this:

var    
  s1,s2:  String[200];
  sp: PAnsiChar;
begin
// sp:=@s2[1]; When I uncomment this, fucntion works as
//  expected, otherwice return string s2 is empty!
   res:=DAQmxGetPhysicalChanName(taskHandle,@s1[1],@s2[1],200);

The function works only when I insert sp:=@s2[1] before the call. I never actually use the sp pointer, but just the fact that it get assigned helps. Without that, the s2 string is empty. I cant understand why. What am I doing wrong?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Michael Gendelev
  • 471
  • 4
  • 16
  • 1
    Try using `s1, s2: array[0..199] of AnsiChar` instead of `s1, s2: String[200]`, and then replace `@s1[1]` and `@s2[1]` with `@s1[0]` and `@s2[0]`, or just `s1` and `s2` without any indexing. – Remy Lebeau Apr 14 '17 at 00:24
  • Thanks, just tested - it works correctly! But I dont really understand what's the difference? In both cases we pass pointers to arrays of bytes, which arrays calling DLL fills as null-terminated string? I mean, are C types const char and char * equal while translating in Delphi and equal to Pascal byte (char) array? – Michael Gendelev Apr 14 '17 at 00:37
  • 3
    `String[200]` defines a 200-character `ShortString`, which is physically 201 bytes in memory. The first byte is the string length. You are passing a pointer to the string's character memory, and the function can populate that with data all it wants, but you are not setting the string length byte afterwards, so it is still 0, giving the illusion that the string is blank. A raw `array[] of AnsiChar` has no such length byte. – Remy Lebeau Apr 14 '17 at 00:49
  • Oh, now its clear, many thanks! Just forgot about that length might be incorrect. – Michael Gendelev Apr 14 '17 at 00:53

0 Answers0