Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C – Passing argv[x] to Function as wchar_t

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading