Equivalent struct declaration in Zig - struct

How would you declare the following struct equivalently in Zig?
static struct lws_protocols protocols[] = {
{ "http", lws_callback_http_dummy, 0, 0 },
LWS_PLUGIN_PROTOCOL_MINIMAL,
{ NULL, NULL, 0, 0 } /* terminator */
};
Looking at the LWS_PLUGIN_PROTOCOL_MINIMAL, it's defined in a header as:
#define LWS_PLUGIN_PROTOCOL_MINIMAL \
{ \
"lws-minimal-proxy", \
callback_minimal, \
sizeof(struct per_session_data__minimal), \
128, \
0, NULL, 0 \
}
and
struct lws_protocols {
const char *name;
lws_callback_function *callback;
size_t per_session_data_size;
size_t rx_buffer_size;
unsigned int id;
void *user;
size_t tx_packet_size;
};

I used zig translate-c -l libwebsockets minimal-ws-server.c > foo.zig to produce a zig source file from the original C source.
I then looked through the foo.zig file and extracted the following:
pub const struct_lws_protocols = extern struct {
name: [*c]const u8,
callback: ?lws.lws_callback_function,
per_session_data_size: usize,
rx_buffer_size: usize,
id: c_uint,
user: ?*c_void,
tx_packet_size: usize,
};
pub var protocols: [0]struct_lws_protocols = [0]struct_lws_protocols{
struct_lws_protocols{
.name = "http",
.callback = lws.lws_callback_http_dummy,
.per_session_data_size = #bitCast(usize, #as(c_long, #as(c_int, 0))),
.rx_buffer_size = #bitCast(usize, #as(c_long, #as(c_int, 0))),
.id = 0,
.user = null,
.tx_packet_size = 0,
},
};
I then discovered that using the zig C header import:
const lws = #cImport(#cInclude("libwebsockets.h"));
I could just reference the structs (or other definitions) provided by the header by prefixing the names with lws. e.g. lws.lws_callback_http_dummy (as used above) rather than duplicating those definitions in my zig source

Related

In Rcpp, how to get a user-defined structure from C into R

Am using Rcpp packages and can get my C function to compile and run in R, but now I want to return a large, user-defined data structure to R. The fields in the structure are either numbers or strings - no new or odd types within the structure. The example below is simplified and doesn't compile, but it conveys the idea of my problem.
typedef struct {
char* firstname[128];
char* lastname[128];
int nbrOfSamples;
} HEADER_INFO;
// [[Rcpp::export]]
HEADER_INFO* read_header(Rcpp::StringVector strings) {
FILE *fp;
MEF_HEADER_INFO *header;
char * filename = (char*)(strings(0));
char * password = (char*)(strings(1));
header = (HEADER_INFO*)malloc(sizeof(HEADER_INFO));
memset(header, 0, sizeof(HEADER_INFO));
fp = fopen(filename, "r");
(void)read_header(header, password);
return header;
}
I'm pretty sure that I could package the entries in the header back into a StringVector, but that seems like a brute-force approach. My question is whether a more elegant solution exists. It is not clear to me what form such a structure would even have in R: a named List?
Thanks!
The right structure in R depends on what your struct looks like exactly. A named list is the most general one. Here a simple sample implementation for a wrap function as referred to in the comments:
#include <RcppCommon.h>
typedef struct {
char* firstname[128];
char* lastname[128];
int nbrOfSamples;
} HEADER_INFO;
namespace Rcpp {
template <>
SEXP wrap(const HEADER_INFO& x);
}
#include <Rcpp.h>
namespace Rcpp {
template <>
SEXP wrap(const HEADER_INFO& x) {
Rcpp::CharacterVector firstname(x.firstname, x.firstname + x.nbrOfSamples);
Rcpp::CharacterVector lastname(x.lastname, x.lastname + x.nbrOfSamples);
return Rcpp::wrap(Rcpp::List::create(Rcpp::Named("firstname") = firstname,
Rcpp::Named("lastname") = lastname,
Rcpp::Named("nbrOfSamples") = Rcpp::wrap(x.nbrOfSamples)));
};
}
// [[Rcpp::export]]
HEADER_INFO getHeaderInfo() {
HEADER_INFO header;
header.firstname[0] = (char*)"Albert";
header.lastname[0] = (char*)"Einstein";
header.firstname[1] = (char*)"Niels";
header.lastname[1] = (char*)"Bohr";
header.firstname[2] = (char*)"Werner";
header.lastname[2] = (char*)"Heisenberg";
header.nbrOfSamples = 3;
return header;
}
/*** R
getHeaderInfo()
*/
Output:
> getHeaderInfo()
$firstname
[1] "Albert" "Niels" "Werner"
$lastname
[1] "Einstein" "Bohr" "Heisenberg"
$nbrOfSamples
[1] 3
However, for this particular case a data.frame would be more natural to use, which can be achieved by replacing above wrap with:
template <>
SEXP wrap(const HEADER_INFO& x) {
Rcpp::CharacterVector firstname(x.firstname, x.firstname + x.nbrOfSamples);
Rcpp::CharacterVector lastname(x.lastname, x.lastname + x.nbrOfSamples);
return Rcpp::wrap(Rcpp::DataFrame::create(Rcpp::Named("firstname") = firstname,
Rcpp::Named("lastname") = lastname));
};
Output:
> getHeaderInfo()
firstname lastname
1 Albert Einstein
2 Niels Bohr
3 Werner Heisenberg

Access a struct property by its name as a string in Swift

Let's say I have the following struct in Swift:
struct Data {
let old: Double
let new: Double
}
Now I have a class with an array of Data structs:
class MyClass {
var myDataArray: [Data]
}
Now let's say I want to calculate the average of either the old or the new values:
func calculateAverage(oldOrNew: String) -> Double {
var total = 0.0
count = 0
for data in myDataArray {
total += data.oldOrNew
count++
}
return total / Double(count)
}
And then:
let oldAverage = calculateAverage("old")
let newAverage = calculateAverage("new")
But this obviously doesn't work, since oldOrNew is not a member of my struct.
How can I access old or new from "old" or "new" ?
What about this "reflection-less" solution?
struct Data {
let old: Double
let new: Double
func valueByPropertyName(name:String) -> Double {
switch name {
case "old": return old
case "new": return new
default: fatalError("Wrong property name")
}
}
}
Now you can do this
let data = Data(old: 0, new: 1)
data.valueByPropertyName("old") // 0
data.valueByPropertyName("new") // 1
You're looking for key-value-coding (KVC) that is accessing properties by key (path).
Short answer: A struct does not support KVC.
If the struct is not mandatory in your design use a subclass of NSObject there you get KVC and even operators like #avg for free.
class MyData : NSObject {
#objc let old, new: Double
init(old:Double, new:Double) {
self.old = old
self.new = new
}
}
let myDataArray : NSArray = [MyData(old: 1, new: 3), MyData(old:5, new: 9), MyData(old: 12, new: 66)]
let averageOld = myDataArray.value(forKeyPath:"#avg.old")
let averageNew = myDataArray.value(forKeyPath: "#avg.new")
Edit: In Swift 4 a struct does support Swift KVC but the operator #avg is not available
You wouldn't access a struct property by name in Swift any more than you would in C++. You'd provide a block.
Extemporaneous:
func calculateAverage(getter: (Data) -> Double) {
... total += getter(data) ...
}
...
calculateAverage({$0.old})
calculateAverage({$0.new})
Possibly with average {$0.old} being a more natural syntax — the verb isn't really helpful and if you're asserting what it is, not what the computer should do, then omitting the brackets looks fine.

Convert an String to an array of int8

I have an C struct (old library, blah blah blah) which contains an C string, now I need to convert CFString and Swift strings into this c string. Something like
struct Product{
char name[50];
char code[20];
}
So I'm trying to assign it as
productName.getCString(&myVarOfStructProduct.name, maxLength: 50, encoding: NSUTF8StringEncoding)
but the compiler is giving me the following error: cannot convert type (int8, int8, int8....) to [CChar].
A possible solution:
withUnsafeMutablePointer(&myVarOfStructProduct.name) {
strlcpy(UnsafeMutablePointer($0), productName, UInt(sizeofValue(myVarOfStructProduct.name)))
}
Inside the block, $0 is a (mutable) pointer to the tuple. This pointer is
converted to an UnsafeMutablePointer<Int8> as expected by the
BSD library function strlcpy().
It also uses the fact that the Swift string productName is automatically
to UnsafePointer<UInt8>
as explained in String value to UnsafePointer<UInt8> function parameter behavior. As mentioned in the comments in that
thread, this is done by creating a temporary UInt8 array (or sequence?).
So alternatively you could enumerate the UTF-8 bytes explicitly and put them
into the destination:
withUnsafeMutablePointer(&myVarOfStructProduct.name) {
tuplePtr -> Void in
var uint8Ptr = UnsafeMutablePointer<UInt8>(tuplePtr)
let size = sizeofValue(myVarOfStructProduct.name)
var idx = 0
if size == 0 { return } // C array has zero length.
for u in productName.utf8 {
if idx == size - 1 { break }
uint8Ptr[idx++] = u
}
uint8Ptr[idx] = 0 // NUL-terminate the C string in the array.
}
Yet another possible solution (with an intermediate NSData object):
withUnsafeMutablePointer(&myVarOfStructProduct.name) {
tuplePtr -> Void in
let tmp = productName + String(UnicodeScalar(0)) // Add NUL-termination
let data = tmp.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
data.getBytes(tuplePtr, length: sizeofValue(myVarOfStructProduct.name))
}
Update for Swift 3:
withUnsafeMutablePointer(to: &myVarOfStructProduct.name) {
$0.withMemoryRebound(to: Int8.self, capacity: MemoryLayout.size(ofValue: myVarOfStructProduct.name)) {
_ = strlcpy($0, productName, MemoryLayout.size(ofValue: myVarOfStructProduct.name))
}
}

Difference between spi_driver.id_table and spi_driver.driver.of_match_table

I'm currently trying to understand how linux drivers work. As far as I know, A driver's probe/init function is called when the kernel parses the corresponding .compatible string in the device tree. However, in the arizona-spi driver it looks like there are multiple compatible strings referenced in different members:
static const struct spi_device_id arizona_spi_ids[] = {
{ "wm5102", WM5102 },
{ "wm5110", WM5110 },
{ },
};
MODULE_DEVICE_TABLE(spi, arizona_spi_ids);
static struct spi_driver arizona_spi_driver = {
.driver = {
.name = "arizona",
.owner = THIS_MODULE,
.pm = &arizona_pm_ops,
// Contains e.g. "wlf,wm5102"
.of_match_table = of_match_ptr(arizona_of_match),
},
.probe = arizona_spi_probe,
.remove = arizona_spi_remove,
.id_table = arizona_spi_ids, // Contains "wm5102" and "wm5110"
};
This is an excerpt from here.
So what is the difference between arizona_spi_driver.id_table and arizona_spi_driver.driver.of_match_table?
There are several mechanism for driver matching. The id_table is intended to be used for finding a match from stripped device-tree entries (without vendor part), while of_match_table is used to find a match from full device-tree entries (the ones with vendor part).
If you check, arizona_of_match is defined as this:
const struct of_device_id arizona_of_match[] = {
{ .compatible = "wlf,wm5102", .data = (void *)WM5102 },
{ .compatible = "wlf,wm5110", .data = (void *)WM5110 },
{ .compatible = "wlf,wm8280", .data = (void *)WM8280 },
{ .compatible = "wlf,wm8997", .data = (void *)WM8997 },
{},
};
wlf is the vendor part for this case, while arizona_spi_ids doesn't contain the vendor part.
Hence, if you have something like this in your device tree:
compatible = "myvendor,wm5102"
Your device will match against id_table but not against of_match_table since the vendor is different.
The kernel will do matching against of_match_table first before check id_table (see spi_get_device_id in here). The device matching priority is: of_match_table > acpi_driver > id_table.

How to change LED trigger?

I have register in BSP's the LED:
static struct gpio_led ic_leds[] = {
{
.name = "led1:green",
.gpio = USER_LED,
.default_trigger = "heartbeat",
.active_low = 1,
},
};
static struct gpio_led_platform_data ic_led_info = {
.num_leds = ARRAY_SIZE(ic_leds),
.leds = ic_leds,
};
static struct platform_device ic_leds_device = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &ic_led_info,
},
};
static void __init ic_add_device_leds(void)
{
platform_device_register(&ic_leds_device);
}
How can I change the trigger in run time? I know that it's possible with sysfs, but maybe exist another way?
echo "thetriggeryouwant" > /sys/class/leds/someled/trigger
where thetriggeryouwant is for example phy0rx and someled is the name of the led you want to change the trigger for.
To get all available triggers for that led, you can cat the file:
cat /sys/class/leds/someled/trigger
gives for example:
[none] timer oneshot mtd nand-disk heartbeat backlight gpio cpu cpu0 cpu1 activity default-on 2188000.ethernet-2:00:link 2188000.ethernet-2:00:100Mbps 2188000.ethernet-2:00:10Mbps
where the item in brackets ([none]) denotes the current trigger.

Resources