How to get a "PCWSTR" object from a Path or String? - winapi

I'm using the IDesktopWallpaper::SetWallpaper method from the windows crate. The second argument to this method is a PCWSTR(pointer) to the full path of an image that's meant to be set as the wallpaper. The problem is that the PCWSTR object is meant to be of type *const u16 not *const String. How can I get a PCWSTR object from a Path/String?
let path = "Path_to_image.jpg".to_string();
let ptr = &path as *const String;
let wallpaper = PCWSTR::from_raw(ptr);
// ^^^ expected raw pointer `*const u16`
// found raw pointer `*const String`
unsafe { desktop.SetWallpaper(None, wallpaper)};

When it comes to strings, Rust and Windows couldn't possibly disagree more. There's always going to be conversions involved when using Rust on Windows, and the best you can hope for is a crate that does this for you.
The windows crate doesn't just provide Rust mappings for Windows' API surface, it also contains a tiny library that addresses common issues when programming Windows with Rust, amongst which is string handling. A lot of thought went into string handling, and the result may seem somewhat anticlimactic: All string constants can be represented as HSTRING instances.
Consequently, HSTRING is the pivot point for string conversions in Rust for Windows. Its implementation has a sleuth of From trait implementations for Rust string types (all, I believe), with From implementations of all other Windows string types for HSTRING.
In this case, if path is of type Path you can simply construct an HSTRING from it, and pass it by reference. Everything else just happens due to implicit From trait invocations (namely From<&HSTRING> for PCWSTR):
unsafe { desktop.SetWallpaper(None, &HSTRING::from(path.as_os_str())) };

Related

Return Ruby's Fiddle::Pointer from C function

I am currently working on a high-performance Vector/Matrix Ruby gem C extension, as I find the built-in implementation cumbersome and not ideal for most cases that I have personally encountered, as well as lacking in other areas.
My first approach was implementing in Ruby as a subclass of Fiddle::CStructEntity, as a goal is to make them optimized for interop without need for conversion (such as passing to native OpenGL functions). Implementing in C offers a great benefit for the math, but I ran into a roadblock when trying to implement a minor function.
I wished to have a method return a Fiddle::Pointer to the struct (basically a pointer to Rdata->data. I wished to return an actual Fiddle::Pointer object. Returning an integer address, packed string, etc. is trivial, and using that could easily be extended in a Ruby method to convert to a Fiddle::Pointer like this:
def ptr
# Assume address is an integer address returned from C
Fiddle::Pointer.new(self.address, self.size)
end
This kind of opened up a question to me, and that is it possible to to even do such from C? Fiddle is not part of the core, library, it is part of the standard lib, and as such, is really just an extension itself.
The problem is trivial, and can be easily overcome with a couple lines of Ruby code as demonstrated above, but was more curious if returning a Fiddle object was even possible from a C extension without hacks? I was unable to find any examples of this being done, and as always when it comes to the documentation involving Fiddle, it is quite basic and does not explain much.
The solution for this is actually rather simple, though admittedly not as elegant or clean of a solution I was hoping to discover.
There are possibly more elaborate ways to go about this by including the headers for Fiddle, and building against it, but this was not really a viable solution, as I didn't want to restrict my C extension to only work with Ruby 2.0+, and would be perfectly acceptable to simply omit the method in the event Ruby version was less than 2.0.
First I include version.h, which gives access defines the macro RUBY_API_VERSION_MAJOR, which is all I really need to know in regards to whether or not Fiddle will be present or not.
This will be an abbreviated version to simply show how to get the Fiddle::Pointer class as a VALUE, and to create an instance.
#if RUBY_API_VERSION_MAJOR >= 2
rb_require("fiddle");
VALUE fiddle = rb_const_get(rb_cObject, rb_intern("Fiddle"));
rb_cFiddlePointer = rb_const_get(fiddle, rb_intern("Pointer"));
#endif
In this example, the class is stored in rb_cFiddlePointer, which can then be used to create and return a Fiddle::Pointer object from C.
// Get basic data about the struct
struct RData *rdata = RDATA(self);
VALUE *args = xmalloc(sizeof(VALUE) * 2);
// Set the platform pointer-size address (could just use size_t here...)
#if SIZEOF_INTPTR_T == 4
args[0] = LONG2NUM((long) rdata->data);
#elif SIZEOF_INTPTR_T == 8
args[0] = LL2NUM((long long) rdata->data);
#else
args[0] = INT2NUM(0);
#endif
// Get size of structure
args[1] = INT2NUM(SIZE_OF_YOUR_STRUCTURE);
VALUE ptr = rb_class_new_instance(2, args, rb_cFiddlePointer);
xfree(args);
return ptr;
After linking the function to an actual Ruby method, you can then call it to get a sized pointer to the internal structure in memory.

Access the raw bytes of a string

I'm trying to call a C function that expects a C string (char*) from go. I know about the C.CString function documented in the cgo documentation but as the function I'm calling will already make a copy, I'm trying to avoid the one Cstring makes.
Right now, I'm doing this, s being a go string
var cs *C.char = (*C.char)( unsafe.Pointer(& []byte(s) [0]))
But I get the feeling that the []bytes(s) is making its own copy. Is it possible to just get the char* ?
If you're doing this enough times that performance is a concern, it would really be advisable to keep the data in a slice to begin with.
If you really want to access to the address of the string, you can use the unsafe package to convert it into a struct matching the string header. Using the reflect.StringHeader type:
p := unsafe.Pointer((*(*reflect.StringHeader)(unsafe.Pointer(&s))).Data)
Or using a slice as a proxy, since they both put the data pointer and length integers in the same field locations
p := unsafe.Pointer(&(*(*[]byte)(unsafe.Pointer(&s)))[0])
Or because the data pointer is first, you could use a uintptr alone
p := unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&s)))
https://play.golang.org/p/ps1Py7Ax6QK
None of these ways are guaranteed to work in all cases, or in future versions of Go, and none of the options are going to guarantee a null terminated string.
The best, supported option is to create a shim in the cgo preamble to accept the go string, and convert it to a *char. CGO provides access to the following function to do this:
const char *_GoStringPtr(_GoString_ s);
See the Go references to C section in the documentation.

When should I use static data members vs. const global variables?

Declaring const global variables has proven useful to determine some functioning parameters of an API. For example, on my API, the minimum order of numerical accuracy operators have is 2; thus, I declare:
const int kDefaultOrderAccuracy{2};
as a global variable. Would it be better to make this a static const public data member of the classes describing these operators? When, in general, is better to choose one over the other?
const int kDefaultOrderAccuracy{2};
is the declaration of a static variable: kDefaultOrderAccuracy has internal linkage. Putting names with internal linkage in a header is obviously an extremely bad idea, making it extremely easy to violate the One Definition Rule (ODR) in other code with external linkage in the same or other header, notably when the name is used in the body of an inline or template function:
Inside f.hpp:
template <typename T>
const T& max(const T &x, const T &y) {
return x>y ? x : y;
}
inline int f(int x) {
return max(kDefaultOrderAccuracy, x); // which kDefaultOrderAccuracy?
}
As soon as you include f.hpp in two TU (Translation Units), you violate the ODR, as the definition is not unique, as it uses a namespace static variable: which kDefaultOrderAccuracy object the definition designates depends on the TU in which it is compiled.
A static member of a class has external linkage:
struct constants {
static const int kDefaultOrderAccuracy{2};
};
inline int f(int x) {
return max(constants::kDefaultOrderAccuracy, x); // OK
}
There is only one constants::kDefaultOrderAccuracy in the program.
You can also use namespace level global constant objects:
extern const int kDefaultOrderAccuracy;
Context is always important.
To answer questions like this.
Also for naming itself.
If you as a reader (co-coder) need to guess what an identifier means, you start looking for more context, this may be supported through an API doc, often included in decent IDEs. But if you didn't provide a really great API doc (I read this from your question), the only context you get is by looking where your declaration is placed.
Here you may be interested in the name(s) of the containing library, subdirectory, file, namespace, or class, and last not least in the type being used.
If I read kDefaultOrderAccuracy, I see a lot of context encoded (Default, Order, Accuracy), where Order could be related for sales or sorting, and the k encoding doesn't say anything to me. Just to make you looking on your actual problem from a different perspective. C/C++ Identifiers have a poor grammar: they are restricted to rules for compound words.
This limitation of global identifiers is the most important reason why I mostly avoid global variables, even constants, sometimes even types. If its the meaning is limited to a given context, define a thing right within this context. Sometimes you first have to create this context.
Your explanation contains some unused context:
numerical operators
minimum precision (BTW: minimum doesn't mean default)
The problem of placing a definition into the right class is not very different from the problem to find the right place for a global: you have to find/create the right header file (and/or namespace).
As a side note, you may be interested to learn that also enum can be used to get cheap compile-time constants, and enums can also be placed into classes (or namespaces). Also a scoped enumeration is an option you should consider before introducing global constants. As with enclosing class definitions, the :: is a means of punctuation which separates more than _ or an in-word caseChange.
Addendum:
If you are interested in providing a useful default behaviour of your operations that can be overridden by your users, default arguments could be an option. If your API provides operators, you should study how the input/output manipulators for the standard I/O streams work.
my guess is that:
const takes up inline memory based on size of data value such as “mov ah, const value” for each use, which can be a really short command, in size overall, overall, based on input value.
whereas static values takes up a whole full data type, usually int, whatever that maybe on the current system for each static, maybe more, plus it may need a full memory access value to access the data, such as mov ah, [memory pointer], which is usually size of int on the system, for each use (with a full class it could even more complex). yet the static is still declared const so it may behave the same as the normal const type.

Swift Generics: More specialized than generic?

XCode 6: Beta 5:
Goal:
I am trying to write generic code for types that are semantically compatible but do not share (or appear to share) sufficient protocols to base my generics on a subset of shared protocols. So far, I have not been able to find a solution, and am wondering I am missing something or if it is a limitation of the language - any insight is appreciated.
Problem:
I have some functions that differ only by type and not by semantics and seem like a natural fit for generics. The problem that I am having, is that from what I can tell, Swift does what seems like parse-time binding of generics, failing if there could conceivably be a problem, and not when there actually is one.
Example:
Consider the following generic functions in a contrived example:
func defVal<T where T:FloatingPointType, T:FloatLiteralConvertible>(T.Type) -> T {
return 0.0
}
func defVal<T:IntegerLiteralConvertible>(T.Type) -> T {
return 0
}
Note that I have provided functions that should span the cases of integers and floats, and intentionally did not want to provide an exhaustive list of all possible variations that are of no relevance to me.
I then want to define generic code that spans types - in this example, int and float types. Note that this code fails to compile even in the absence of any code that calls it:
func doSomethingGeneric<T>(t:T) -> [T]
{
let a = defVal(T) // Type 'T' does not conform to protocol FloatLiteralConvertible
let b = a * a // works
return [t]
}
In my recollection, this would compile in C++ until you called it with an incompatible type, at which point the compiler would catch it.
I also tried other variants of diminished utility:
func doSomethingWithFloats<T
where T:FloatingPointType, T:FloatLiteralConvertible>(t:T) -> [T]
{
let a = defVal(T) // works
let b = a * a // T is not convertible to UInt8
// - need a floating point arithmetic type?
let c = -a // T is not convertible to Float
let f:Float = -a // T is not convertible to Float
return [t]
}
Given the sense that Swift provides protocols as a way of grouping concrete instances (specialized, not generic), I concocted a protocludge:
protocol Initializable {}
extension Float : Initializable {}
extension Double : Initializable {}
extension CGFloat : Initializable {}
func doSomethingWithInitializable<T:Initializable>(t:T) -> [T]
{
let a = defVal(T) // Type 'T' does not conform to protocol FloatLiteralConvertible
let b = a * a // works
return [t]
}
Note that this fails even though FloatLiteralConvertible is implemented across the set of all Initializable types. Put another way, Swift seems to be binding the generic types too early, and treating generic types as if they were specialized concrete instances instead of a greater pattern that would compile out further down the chain. Furthermore, note that while I could derive from FloatLiteralConvertible, this would preclude me from supporting int types etc. If there was a common ArithmeticType protocol, that could conceivably work, but I do not see anything of the sort. And this is the crux of the problem - there is no common protocol that works for both, even though both ints and floating types are semantically compatible (have the same rules of math).
So in summary, how do you write generic functions for which the types are semantically compatible, but for which there are not enough spanning protocols to filter by protocol (in this case - FloatingPointType does not implement IntegerArithmeticType, but is semantically capable of arithmetic).
Thanks in advance.
Unlike C++, Swift does not deal with generics by substituting the concrete types at the call site and making a non-generic copy (at least in general it doesn't - as an optimization that's allowed, but I digress)
Swift deals with genericity by passing in metadata information describing the actual types at each invocation into one master function, which then uses metadata-provided entry points to manipulate your objects
In your example, Initializable does not provide any operations, so when the compiler tries to execute defVal(T) it has no clue what to do (how can it ensure that there is an overload of defVal for your type?)
What you want to do is actually define defVal as a static function on the Initializable protocol, and then implement it in the extensions, then Swift will know that T.defVal() means something akin to
metadata[Initializable]->defVal(metadata)
Oh, since you're trying to execute a *(T,T), you might also want to make a Multipliable protocol and then your T will be typed as
<T: protocol<Initializable,Multipliable>>

Understanding MAKEINTRESOURCEW definition

Looking at the Windows SDK, I found this #define directive for MAKEINTRESOURCEW:
#define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i))))
Can someone explain to me what the heck that means? For example, what would be the value of MAKEINTRESOURCEW(0)? (1)? (-1)?
The result of this macro will be pointer to long string with value equal to given parameter. You can see it by reading precompiler output (see /P C++ compiler options). All casting is required to compile this macro result, when LP[w]WSTR pointer is required, both in Win32 and x64 configurations.
Some Windows API, like LoadIcon, expect string pointer as their parameter. Possibly, these functions test the pointer value, and if it is less than some maximum, they interpret it as resource index, and not as string (problems of ugly C-style interface). So, this macro allows to pass WORD as string, without changing its value, with appropriate casting.
For the most part, it leaves the value unchanged, but converts it from an int to a pointer so it's acceptable to functions that expect to see a pointer. The intermediate casts widen the input int to the same size as a pointer, while ensuring against it's being sign extended. In case you care, ULONG_PTR is not a "ULONG POINTER" like you might guess -- rather, it's an unsigned long the same size as a pointer. Back before 64-bit programming became a concern, the definition was something like:
#define MAKEINTRESOURCE(i) (LPTSTR) ((DWORD) ((WORD) (i)))
Nowadays, they use ULONG_PTR, which is a 32-bit unsigned long for a 32-bit target, and a 64-bit unsigned long for a 64-bit target.
That's a macro that casts an argument i to a word, then casts that result to a pointer to an unsigned long, then again to a long pointer to a wide-character string.
Like other users said - it just casts an integer into a "pointer to a string".
The reason for this is the following: At the ancient times of Windows 3.0 people tried to be minimalistic as much as possible.
It was assumed that resources in the executable can have either string identifier or integer. Hence when you try to access such a resource - you specify one of the above, and the function distinguish what you meant automatically (by checking if the provided "pointer" looks like a valid pointer).
Since the function could not receive a "variable argument type" - they decided to make it receive LPCTSTR (or similar), whereas the actual parameter passed may be integer.
Another example from Windows API: A pointer to the window procedure. Every window has a window procedure (accessed via GetWindowLong with GWL_WNDPROC flag.
However sometimes it's just an integer which specifies what "kind" of a window is that.
Then there's a CallWindowProc which knows to distinguish those cases.

Resources