I'm trying to write some code that uses hidapi to do with some USB lights. The function within hidapi expects the serial_number to be passed as wchar_t, however my argv[] are char*
The way it DOES work is to hard code the SERIALNUMBER and use wcsncpy()
wcsncpy(serial_number, L"SERIALNUMBER", MAX_STR);
dev = hid_open(0x046d, 0xc900, serial_number);
The way it does NOT work is to send the serial number as a CLI argument (e.g. ./script SERIALNUMBER
), after using a function to convert the char* to a wchar_t:
void ctow(char *toConvert, wchar_t *wstr) {
int count = 0;
int len = strlen(toConvert);
for(; count < len; count ) {
wstr[count] = (wchar_t) toConvert[count];
}
}
What's weird is that when you wprintf()
the serial number it does come out correctly. I also noticed that if you don't add the L
to the hard coded serial number it also doesn't work.
This is part of a much larger program, but I've whittled it down to just the immediate use case for troubleshooting. What am I doing wrong, here? Here is the full code:
#include <string.h>
#include <hidapi.h>
#define MAX_STR 255
void ctow(char *toConvert, wchar_t *wstr) {
int count = 0;
int len = strlen(toConvert);
for(; count < len; count ) {
wstr[count] = (wchar_t) toConvert[count];
}
}
int main(int argc, char* argv[])
{
wchar_t wstr[MAX_STR];
wchar_t serial_number[MAX_STR];
hid_device *dev;
// ctow(argv[1],serial_number); // this DOES NOT WORK
wcsncpy(serial_number, L"SERIALNUMBER", MAX_STR); // this DOES work
dev = hid_open(0x046d, 0xc900, serial_number);
if (!dev) {
wprintf(L"Open FAILED on serial number %ls", serial_number);
}
else {
wprintf(L"Open SUCCESS on serial number %ls", serial_number);
}
return 0;
}
CodePudding user response:
Use mbstowcs
char* foo = "abcdef";
wchar_t *wfoo = malloc((strlen(foo) 1) * sizeof(wchar_t));
mbstowcs(wfoo, foo, strlen(foo) 1);
see en.cppreference.com/w/c/string/multibyte/mbstowcs