Z
Z
Zakhar Alekseenko2015-06-02 19:32:06
Delphi
Zakhar Alekseenko, 2015-06-02 19:32:06

How to initialize PCHAR string in c++?

Hello.
I am making a program using the Qt5.4 framework. I am using a third party library written in delphi. One of the functions accepts a PCHAR type. I am unable to create and initialize a variable of type PCHAR. To create the desired line used various methods

char ss[]="usb3000";
char *s = ss;
PCHAR* p =reinterpret_cast<PCHAR*>(s);

PCHAR tx[]={{'u'},{'s'},{'b'},{'3'},{'0'},{'0'},{'0'}};

PCHAR tx[]=L"usb3000";
None of the options above worked correctly. The first one fell out with a segmentation fault when calling a function from the library. The compiler swears at the rest.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sumor, 2015-06-02
@Sumor

No one can tell you exactly - you need to experiment.
The options are as follows:
Delphi expects not the usual PChar, but its own String or AnsiString, which implies the size of the string in the first byte or two bytes. You pass a character there that is obviously larger than the size of the string, and delphi reads extra memory and crashes.
Less likely options are unicode is expected, or you end up with unicode.

D
DISaccount, 2015-06-02
@DISaccount

PChar is already a pointer. So you should have a typedef like this:

typedef char* PCHAR;
...........

char ss[]="usb3000";
PCHAR p =reinterpret_cast<PCHAR>(ss);

T
to_climb, 2015-06-02
@to_climb

As already written, a segmentation fault is an out of bounds memory allocation. Surely the function writes something to this line (although it can read beyond its border, but less likely - zero at the end after all). The recipe is simple - you need to understand what size the string is expected to be and allocate the required size using new. A common practice is to pass NULL first instead of a buffer so that the function returns the expected desired size.

M
Mercury13, 2015-06-02
@Mercury13

1. What does the system accept: PCHAR or PCHAR*?
2. If the versions of Delphi are new enough, PCHAR is most likely wchar_t* and you just need to pass the "wide" string L"usb3000".
3. Try not to have reinterpret_cast; it is a sign that you are doing something wrong. The only place where it is valid in such APIs is in callbacks for passing a closure (information about which subroutine and under what circumstances launched the function that called the callback). PS I also thought of the second purpose of reinterpret_cast - a function that can receive data of different types (like SendMessage from Win32).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question