I try import windows API CharToOem function

Adam D. Ruppe destructionator at gmail.com
Mon Aug 26 11:02:49 PDT 2013


On Monday, 26 August 2013 at 17:42:49 UTC, Quentin J. wrote:
> extern (Windows) bool CharToOem(const char*, char*);

Try:

// use the unicode version of the Windows function
extern (Windows) bool CharToOemW(const wchar*, char*);
alias CharToOemW CharToOem;


Windows functions often have an A or a W at the end of them, for 
ascii or wide char version. The name without A or W is just an 
alias or #define for many functions.

Your function is wrong too:

> 	char[] source = text.dup;

This might not zero terminate the string, and won't be right for 
Unicode characters. Better to do:

import std.utf;
auto source = toUTF16z(text);

> 	char[] dest;
>
> 	CharToOem(source.ptr, dest.ptr);

And this will give you an AccessViolation if you run it because 
dest is null.

// allocate some space for the new string first
char[] dest = new char[](text.length * 2);



To to bring it together:

import std.c.windows.windows;

// use the unicode version of the Windows function
extern (Windows) bool CharToOemW(const wchar*, char*);
alias CharToOemW CharToOem;


public void PutStringIntoConsole(string text)
{
         // convert source into a Windows tchar* string
         import std.utf;
         auto source = toUTF16z(text);

         // prepare our buffer with enough space to receive the 
data
         char[] dest = new char[](text.length * 2);

         // call the function...
         CharToOem(source, dest.ptr);

         // we also want to get the length out instead of relying 
on zero termination for a real D string:
         import core.stdc.string;
         dest = dest[0 .. strlen(dest.ptr)];

         writeln(dest);
}



That should give you better results.


More information about the Digitalmars-d mailing list