Unable to pass TCHAR as parameter in C/C++ - c++

Here is Minimal example :-
#include <stdio.h>
#include <Windows.h>
using namespace std;
void myFunc(TCHAR Path)
{
printf("pathLen : %lu\n", sizeof(Path));
printf("character size : %lu\n", sizeof(*Path));
printf("pathLenInBytes : %lu\n", sizeof(Path) * sizeof(*Path));
}
int main()
{
TCHAR selfPath[MAX_PATH];
if (GetModuleFileName(NULL, selfPath, MAX_PATH) == 0) // Getting exe File Location
printf("Error : %lu\n", GetLastError());
printf("Self Path : %s\n", selfPath);
myFunc(selfPath);
return 0;
}
Here is Error Output from MinGW-W64 Compiler :-
g++ -Os -s -o goga.exe tesst.cpp
tesst.cpp: In function 'void myFunc(LPCSTR, TCHAR)':
tesst.cpp:9:43: error: invalid type argument of unary '*' (have 'TCHAR' {aka 'char'})
9 | printf("character size : %lu\n", sizeof(*Path));
| ^~~~
tesst.cpp:10:35: error: 'pathLen' was not declared in this scope
10 | printf("pathLenInBytes : %lu\n", pathLen * sizeof(*Path));
| ^~~~~~~
tesst.cpp:10:53: error: invalid type argument of unary '*' (have 'TCHAR' {aka 'char'})
10 | printf("pathLenInBytes : %lu\n", pathLen * sizeof(*Path));
| ^~~~
tesst.cpp: In function 'int main()':
tesst.cpp:23:22: error: invalid conversion from 'TCHAR*' {aka 'char*'} to 'TCHAR' {aka 'char'} [-fpermissive]
23 | myFunc("AppBroker", selfPath);
| ^~~~~~~~
| |
| TCHAR* {aka char*}
tesst.cpp:6:32: note: initializing argument 2 of 'void myFunc(LPCSTR, TCHAR)'
6 | void myFunc(LPCSTR Name, TCHAR Path)
| ~~~~~~^~~~
But If I put the GetModuleFineName() directy inside myFunc() then it works :-
#include <stdio.h>
#include <Windows.h>
using namespace std;
void myFunc()
{
TCHAR selfPath[MAX_PATH];
if (GetModuleFileName(NULL, selfPath, MAX_PATH) == 0) // Getting exe File Location
printf("Error : %lu\n", GetLastError());
printf("Self Path : %s\n", selfPath);
printf("pathLen : %lu\n", sizeof(selfPath));
printf("character size : %lu\n", sizeof(*selfPath));
printf("pathLenInBytes : %lu\n", sizeof(selfPath) * sizeof(*selfPath));
}
int main()
{
myFunc();
return 0;
}
But I dont need it this way. How can i solve this error ?
EDIT : Tried replacing myFunc(TCHAR Path) with myFunc(TCHAR *Path) & also with myFunc(TCHAR Path[]). Both Work and program compiles successfully but the output is different that expected output now !
Expected Output :-
Self Path : C:\Users\username\Desktop\Coding\PETS\muse\goga.exe
pathLen : 260
character size : 1
pathLenInBytes : 260
Output that I Get:-
Self Path : C:\Users\username\Desktop\Coding\PETS\muse\goga.exe
pathLen : 8
character size : 1
pathLenInBytes : 8

I make an attempt to answer
In your first version, your prototype must be
myFunc(TCHAR *Path) or myFunc(TCHAR Path[]) because a path is an array of TCHAR, thus a TCHAR*
(a starting documentation can be found here or here)
What you obtained from the first code that compiles is only what you have asked.
Let us see:
printf("pathLen : %lu\n", sizeof(Path));
printf("character size : %lu\n", sizeof(*Path));
printf("pathLenInBytes : %lu\n", sizeof(Path) * sizeof(*Path));
First remark: you should not use sizeof (thanks # Remy LEABEAU for review) with TCHAR* but _tcslen() or lstrlen
In the first line, you asked to display the size of path which is a pointer (a TCHAR*). The size
of a pointer can be 4 bytes or 8 bytes depending on your system(ref). So 8 is correct.
In an array, its name is also the adress of the first element in it. Thus if you try to printf
sizeof(*Path), you ask to print the size of the first character pointed by the pointer, thus 1.
The two previous lines also explain what the thrid line gives you: 1*8 = 8.
If pathLenis the size in byte of the path, you may use _tcslen() or lstrlen() to compute the length of the path and then use sizeof(TCHAR) as found here
Proposition to obtain what your needed output:
printf("pathLen : %lu\n", _tcslen(Path));
printf("TCHAR size : %lu\n", sizeof(TCHAR));
printf("pathLenInBytes : %lu\n", _tcslen(Path)* sizeof(*Path));

Related

error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive] in the given set of commands

I have c++ file like below one,
#include <iostream>
using namespace std;
extern "C" {
#include "sample_publish.c"
}
int main()
{
int antenna_id = 123;
send_message_to_mqtt(&antenna_id);
}
I have included a c file in c++ file and I need to pass the variable antenna_id to the function send_message_to_mqtt and the same is in c file like below one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
void send_message_to_mqtt(int *antenna_id) {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, "tcp://mqtt1.mindlogic.com:1883", "ExampleClientPub",
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("DATA FROM C++:::%d\n", *antenna_id);
char payload_data[] = "hi";
//pubmsg.payload = payload_data;
pubmsg.payload = *antenna_id
pubmsg.payloadlen = (int)strlen(*antenna_id);
pubmsg.qos = 1;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "MQTT-Examples", &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %s\n""on topic %s for client with ClientID: %s\n",(int)(10000L/1000), "Hello World!", "MQTT-Examples", "ExampleClientPub");
rc = MQTTClient_waitForCompletion(client, token, 10000L);
printf("Message with delivery token %d delivered\n", token);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
// return rc;
}
When I execute a c++ file, the antenna_id variable is doesnt accessible in c file which in turn not allowing me to map against pubmsg.payload and this is due to the below error,
dell#dell-Inspiron-5379:~/workspace_folder$ g++ sample.cpp -o sample -lpaho-mqtt3c
In file included from sample.cpp:5:0:
sample_publish.c: In function ‘void send_message_to_mqtt(int*)’:
sample_publish.c:30:22: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
pubmsg.payload = *antenna_id
^~~~~~~~~~~
sample_publish.c:31:5: error: expected ‘;’ before ‘pubmsg’
pubmsg.payloadlen = (int)strlen(*antenna_id);
^~~~~~
How to overcome this one?
A guess on the problem, it's most likely this line:
pubmsg.payload = *antenna_id
Besides missing the semicolon, the payload is a pointer to the first byte of the data to be sent. That is, you should not dereference the pointer:
pubmsg.payload = antenna_id;
On a related note, this line is also very wrong:
pubmsg.payloadlen = (int)strlen(*antenna_id);
The strlen function is to get the length if a null-terminate byte string.
The length of an int can be gotten with the sizeof operator:
pubmsg.payloadlen = sizeof *antenna_id;
Note that here you must use the dereference operator, otherwise you get the size of the pointer itself.

error while compiling - conversion from DWORD to LPCVOID

I found this code for injecting dll files and call functions from them. I got an exe and the source code. The exe is working but when i try to compile the source code i get this error:
LoadDll.cpp: In Funktion »bool ExecuteRemoteThread(HANDLE, BOOL, BOOL, wchar_t*, wchar_t*)«:
LoadDll.cpp:313:62: Fehler: ungültige Umwandlung von »DWORD (__attribute__((__stdcall__)) *)(RemoteThreadBlock*) {aka long unsigned int (__attribute__((__stdcall__)) *)(RemoteThreadBlock*)}« in »LPCVOID {aka const void*}« [-fpermissive]
In file included from c:\mingw\bin\../lib/gcc/mingw32/4.7.2/../../../../include/windows.h:50:0,
from LoadDll.cpp:16:
c:\mingw\bin\../lib/gcc/mingw32/4.7.2/../../../../include/winbase.h:2215:24: Fehler: Argument 3 von »BOOL WriteProcessMemory(HANDLE, LPVOID, LPCVOID, SIZE_T, SIZE_T*)« wird initialisiert [-fpermissive]
The source code can be found at: https://pastebin.com/AuZpy57U
It seems like the error is in line 313
if ( ! WriteProcessMemory( hProcess, p, &RemoteThread, 0, 0 ) )
I hope you can help me compiling this.
if ( ! WriteProcessMemory( hProcess, p, &RemoteThread, 0, 0 ) )
You have to cast the third parameter:
if ( !WriteProcessMemory( hProcess, p, reinterpret_cast<LPCVOID>(&RemoteThread), 0, 0 ) )
Update:
To get rid of undefined reference to 'WinMain#16' you should use
int main()
{
int argc;
wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc);
// ...
instead of
int wmain(int argc, wchar_t *argv[])
{
// ...

SHFileOperation error 87

I am trying to copy the contents of the A drive into folder C:\test\disk1. Folder disk1 already exists. The program compiles but when it runs I get error 87. I know error 87 has something to do with an invalid parameter but Im not sure where the problem lies. Has anyone any ideas?
#include <Windows.h>
#include <stdio.h>
int main(int argc, char ** argv)
{
const wchar_t *const sourceFile = L"A:\\";
const wchar_t *const outputFile = L"C:\\test\\disk1";
SHFILEOPSTRUCTW fileOperation;
memset(&fileOperation, 0, sizeof(SHFILEOPSTRUCTW));
fileOperation.wFunc = FO_COPY;
fileOperation.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR |
FOF_NOERRORUI | FOF_FILESONLY;
fileOperation.pFrom = sourceFile;
fileOperation.pTo = outputFile;
int result = SHFileOperationW(&fileOperation);
if (result != 0)
{
printf("SHFileOperation Failure: Error%u\n", result);
return 1;
}
memset(&fileOperation, 0, sizeof(SHFILEOPSTRUCTW));
printf("OK\n");
return 0;
}
Note the documentation of SHFILEOPSTRUCT and in particular that of pFrom and pTo:
PCZZTSTR pFrom;
PCZZTSTR pTo;
What does PCZZTSTR mean?
pFrom
Type: PCZZTSTR
Note This string must be double-null terminated.
So your fix is to supply an additional trailing zero.
const wchar_t *const sourceFile = L"A:\\\0";
const wchar_t *const outputFile = L"C:\\test\\disk1\0";
Note that Windows API functions accept / as a directory separator, so that can be written as the slightly easier to read:
const wchar_t *const sourceFile = L"A:/\0";
const wchar_t *const outputFile = L"C:/test/disk1\0";
(PCZZSTR is actually a pointer to a list of zero terminated strings which is terminated by an empty string.)

Invalid conversion from HANDLE to HINSTANCE (Getting a kernel function's address)

I'm trying to find the address of the SetProcessDEPPolicy function of the Windows API in kernel32 (see my problem here and the first answer I got).
I've never written a Windows C++ program before so I'm a bit lost but I have this so far:
#include <windows.h>
#include <iostream>
int main(int argc, char* argv[])
{
HANDLE kernel32 = GetModuleHandle("kernel32");
FARPROC* funcAddr = (FARPROC *) GetProcAddress(kernel32, "SetProcessDEPPolicy");
std::cout << "# ";
}
I'm getting the following error on line 7:
C:\Documents and Settings\John\Desktop>c++ finddep.cpp -o finddep.exe finddep.cpp: In function 'int main(int, char**)': finddep.cpp:7:79: error: invalid conversion from 'HANDLE {aka void*}' to 'HINSTA NCE' [-fpermissive] FARPROC funcAddr = (FARPROC *) GetProcAddress(kernel32, "SetProcessDEPPolicy") ;
^
In file included from c:\mingw\include\windows.h:50:0,
from finddep.cpp:1: c:\mingw\include\winbase.h:1675:27: error: initializing argument 1 of 'int (__ attribute__((__stdcall__)) * GetProcAddress(HINSTANCE, LPCSTR))()' [-fpermissive ] WINBASEAPI FARPROC WINAPI GetProcAddress(HINSTANCE,LPCSTR);
^ finddep.cpp:7:79: error: cannot convert 'int (__attribute__((__stdcall__)) **)() ' to 'FARPROC {aka int (__attribute__((__stdcall__)) *)()}' in initialization FARPROC funcAddr = (FARPROC *) GetProcAddress(kernel32, "SetProcessDEPPolicy") ;
I couldn't find any good ideas on how to solve this from Google.
(Once I get this to compile, how can I print the address in the pointer?)
EDIT: Added Cyclone's suggestion from the comment, getting same error Invalid conversion from HANDLE to HINSTANCE
This is how you should do it:
#include <windows.h>
#include <iostream>
int main(int argc, char* argv[])
{
HMODULE kernel32 = GetModuleHandleA("kernel32");
FARPROC *funcAddr = (FARPROC *)GetProcAddress(kernel32, "SetProcessDEPPolicy");
std::cout << "#" << funcAddr;
}

File.cpp:148: error: expected primary-expression before ‘.’ token DIFFERENT SYMBOL

I'm struggling to finish this code.
#include (sorry but it won't show up the #include such as stdio.h AND OTHERS) But this is not the problem.
using namespace std;
struct CustomerFile {
int arrivalTime;
string driverfName,
driverlName,
typeOfDriver,
driverLicNumber,
vehicleMake,
vehicleModel,
Lot_taken,
vehicleRegNumber,
attendantName,
ParkingArea,
Comments,
checkOutDateTime,
checkInDateTime;
};
int arrivalTime;
string driverfName,
driverlName,
typeOfDriver,
driverLicNumber,
vehicleMake,
vehicleModel,
Lot_taken,
vehicleRegNumber,
attendantName,
ParkingArea,
Comments,
checkOutDateTime,
checkInDateTime;
int main(int argc, char * * argv) {
FILE * cfPtr;
if ((cfPtr = fopen("CustomerFile.dat", "rb+")) == NULL) {
printf("file could not be opened");
} else {
printf("\nFile is Written to");
printf("\nFile is open");
printf("\n\n\nEnter Vehicle Registration Number: ");
scanf("%s", & CustomerFile.vehicleRegNumber);
while (CustomerFile.vehicleRegNumber != 0) /*#IF THE USER does not enter 0 the loops should begin, but there is a problem here*/
{
printf("\nFirst Name: ");
fscanf("%s", CustomerFile.driverfName); /*here is the problem, I think is had something to do with the struct name*/
printf("\nLast Name: ");
printf("\nType of Driver: ");
printf("\nDriver's License Number: ");
printf("\nVehicle Make: ");
printf("\nVehicle Model: ");
printf("\nComments ");
printf("\nParking SpaceTaken ");
printf("\n\nenter firstname, lastname");
fscanf(stdin, "%s%s%s%s%s%s%s%s1f", CustomerFile.driverfName I think this has something to do with the statement * /
CustomerFile.driverlName / * okay here * /
CustomerFile.typeOfDriver / * okay here * /
CustomerFile.driverLicNumber / * okay here * /
CustomerFile.vehicleMake / * okay here * /
CustomerFile.vehicleModel / * okay here * /
CustomerFile.Comments / * okay here * /
&CustomerFile.Lot_taken); / * okay here * /
fwrite( sizeof(struct CustomerFile ), 1, cfPtr);
}
fclose( cfPtr);
}
return 0;
}
Okay the problem is that it keeps giving the errors;*
File.cpp:144: error: expected primary-expression before ‘.’ token
File.cpp:148: error: expected primary-expression before ‘.’ token
File.cpp:162: error: expected primary-expression before ‘.’ token
File.cpp:172: error: invalid conversion from ‘unsigned int’ to ‘const void*’
File.cpp:172: error: invalid conversion from ‘FILE*’ to ‘size_t’
/usr/include/stdio.h:708: error: too few arguments to function ‘size_t fwrite(const void*, size_t, size_t, FILE*)’
File.cpp:172: error: at this point in file
I believed or read that it has something with the fact that a C++ complier does not work with c99. If so, then how do you use structs in c++? I know you use a struct by just for example CustomerFile.driverlName, however, the complier keep refusing it. Also I'm having problems with the while loop. I'm familiar with c and c++ we were taught both c and c++, the code is to be written in c++ but the text book gives c code that won't run in a c++ complier.
CustomerFile is a class, so it won't work when you try to access data members off of it as if it were an instance. To create an instance, do:
CustomerFile file;
And replace all instances of Customer. with file. and it should resolve the error.
You defined a datatype CustomerFile. For using defined structure CustomerFile you have create an object and use it. For eg :
CustomerFile customer;
customer.vehicleModel = "ABC";
vehicleRegNumber is of type string not integer compare it with 0 like this
while (customer.vehicleRegNumber != "0" )
Add , between variable names
fscanf( stdin, "%s%s%s%s%s%s%s%s1f", customer.driverfName, customer.driverlName ,
The fscanf() function is a C function, it does not know about std::string (or classes). So you have use a temp c string like this
char temp[100];
printf("\nFirst Name: ");
fscanf(stdin, "%99s", temp );
customer.driverfName = temp;