Please take a look to the pthread_create() prototype we have:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
to the last argument is a void pointer. But taking a look in some code in the internet I see developers doing:
long t;
pthread_create( &thread, NULL, function, (void*)t);
and it works!!! I mean they are not doing:
pthread_create( &thread, NULL, function, (void*)&t);
in other words, the reference of "t" is not being used.
However, if I change the datatype to "int" instead "long".. does not work.
I believe the reference should be considered always but do you have idea why long is working with no references?
Thank you guys!
The parameter being passed to the thread function is a void*. In the general case, that pointer can point to some block of data the function can use.
However, remember that the pointer itself is a value. It's common to simply use that value as the data for the thread function if the amount of data you're passing is small enough to fit in a void* - namely if all you need to pass to the function is a integer value. That's what's happening the case:
long t;
t = /* some value to pass to the thread */;
pthread_create( &thread, NULL, function, (void*)t);
One advantage to this is that you don't have lifetime issues to deal with on the thread data.
Related
This is a function in the main.dart file of the just_audio example. I don't understand what's going on with the "ambiguate" line. I understand the bang operator in this context casts to the "underlying type" but in this case there is no underlying type, I don't think. The underlying type is <T?>. I'm only familiar with what that means when I see it in documentation as "a type goes here." If it's in actual code, not sure what it's doing.
void initState() {
super.initState();
ambiguate(WidgetsBinding.instance)!.addObserver(this);
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.black,
));
_init();
}
The ambiguate function from common.dart in the same lib folder:
T? ambiguate<T>(T? value) => value;
https://github.com/ryanheise/just_audio/tree/minor/just_audio/example/lib
The ambiguate function casts a value to its nullable type, so an int is cast to int?.
That allows using the ! (null assert) operator on the value without a warning, because a value of type int cannot be null, so you don't need to assert that it isn't.
The reason for doing so is that in a program which also contains non-null-safe code, the value can actually be null at runtime.
Or because you don't actually know whether the type will be int or int?, because it changed between versions of a library, and you don't want to lock yourself to only the newest version.
Which means that the only reason to use the function is that you expect your code to run against two different and incompatible versions of the same library, one null-safe or non-null-safe where a function can return null, and a newer null-safe version where the function cannot return null and is typed as such.
Then you can do ambiguate(uncertainValue)?.doSomething(), and it does something if the value isn't null, and it compiles against both versions without warning.
If you are not trying to make your code work against two different versions of the same library, which differ in nullability-behavior, then don't use ambiguate.
Even then, consider whether it'd just be easier to require the new version of the library, and lean into null safety.
(This particular use seems unnecessary. Doing ambiguate(something)!.method() will throw an error if the value is null, but so will something.method(), which will also not give any warnings. Well, unless the other version of the library is null safe and returns a nullable value, but then you shouldn't be using ! on it.)
Take this example:
void modl(List<int> l) {
l.add(90);
print(l);
}
class Foo {
final List<int> bar;
const Foo(this.bar);
#override
String toString() => 'Foo{bar: $bar}';
}
void main() {
var foo = const Foo([1,2,3,4]);
modl(foo.bar);
print (foo);
}
Running the above code results in a runtime Uncaught Error, but removing the const from
var foo = const Foo([1,2,3,4]);
allows it to work.
This seems like a bug to me because the const variable can be mutated and dart detects this at runtime, which means it has the means to detect when a const object is modified, but shouldn't this have been detected at compile time, seeing as const variables are called "compile-time constants".
If this is not a bug, is there anything in dart that allows us to detect at compile time when a const variable will possibly be mutated by an operation?
In C++, the compiler errors out when we try to do something like this. Is there anything we can do in Dart to avoid encountering this error at runtime?
No. Dart const is a compile-time feature around object creation, but it's not reflected in the type system.
You can't tell from the type of any object whether it's a constant or not.
Usually that's not a problem because an instance of a class which can be const is unmodifiable. It's not guaranteed to be deeply immutable, but the instance itself cannot have its fields changed.
Lists, sets and maps can both be either constant and mutable. That's what you are seeing here.
The list argument to const Foo(const [1, 2, 3, 4]) is constant, even if you remove the redundant const on the list literal. You would have the same issue with new Foo(const [1, 2, 3, 4]), which would also provide an immutable foo.bar, but which would otherwise be indistinguishable from new Foo([1, 2, 3, 4]). The only real difference is whether the list is modifiable or not, and the only way to detect that is to try to modify it.
Lists, sets and maps do not provide any way to detect whether they are mutable or not except trying, and catching the error.
When comparing to C++, Dart's notion of being const is a property of the object or, really, the way the object is created. That may have some consequences for the object. A const Foo(..) just creates a normal Foo object, but it can only create deeply immutable objects, and they are canonicalized. A const [...] or const {...} creates a different kind of list/map/set than the non-const literal, but that's not visible in the type.
In C++, being const is a property of an object reference, and it restricts how that reference can be used, but there are no constant objects as such. Any object can be passed as a const reference.
The two concepts are completely different in nature, and just happen to use the same name (and are also both different from JavaScript const).
I'm writing a Lua library which registers some metatables using luaL_newmetatable(). Since other libraries might do that as well, I'd like to ask what is a good strategy to avoid having the same name used twice. I was thinking about using a reverse DNS name like com.mydomain.mylibrary which should be pretty safe I guess. However, I'd like to ask if there maybe is a better or standard way of choosing unique names for libraries using luaL_newmetatable().
I like use lightuserdata with pointer to string.
#define LCURL_EASY_NAME LCURL_PREFIX" Easy"
static const char *LCURL_EASY = LCURL_EASY_NAME;
It just requires simple functions to use it.
int lutil_newmetatablep (lua_State *L, const void *p) {
lua_rawgetp(L, LUA_REGISTRYINDEX, p);
if (!lua_isnil(L, -1))
return 0;
lua_pop(L, 1);
lua_newtable(L); /* create metatable */
lua_pushvalue(L, -1); /* duplicate metatable to set*/
lua_rawsetp(L, LUA_REGISTRYINDEX, p);
return 1;
}
Similar for get/set. Checkout e.g. my Lua-cURL library.
I would use a string that describes what is in the "object" as this string is output in Lua error message eventually:
e.g. if the metatable is named "database connection":
stdin:1: bad argument #1 to 'status' (database connection expected, got no value)
If you use a UUID, nobody can make sense of the output.
In Delphi, suppose I have a method with a (much simplified) signature like this:
procedure abc( const prop1:string; const arg1:TValue; const prop2:string;
out arg2:TValue );
I'm building a TList<PPropValPair> of records like this using the parameters provided:
type
TPVPType = (ptIn, ptOut);
PPropValPair = ^TPropValPair;
TPropValPair = record
io : TPVPType;
prop : string; // property name
iVal : TValue; // input value
oVar : Variant; // <-- how to save for later use??? Variant? TValue?
end;
(On the face of it, this example looks silly. Again, it's quite simplified just to communicate the problem.)
At run-time, I want to stuff all of the input values ival (where io=ptIn) into each public property 'prop' in a class, call a class method, then extract the values of all public properites 'prop' (where io=ptOut) into oVar.
The input side is working fine using RTTI.
However, I need to somehow save a REFERENCE to the output vars in oVar so I can save the value of the associated properties after the class method has been called.
I'm not assigning anything to arg2 directly. Rather, I'm saving a reference to arg2 and assigning the value indirectly later on.
The trick is ... I don't want to have to do any additional annotations of the output parameters in abc(...).
In C++, you can declare a parameter as a 'reference' by prepending it with '&'. So in C++ terms this might be defined roughly as:
procedure abc( arg1 : TValue; &arg2 : TValue );
Later, you can refer to &arg2 and it's using a POINTER to the object. But in calling the function, you just say:
abc( somevar1, somevar2 );
somevar1 is passed by value, and somevar2 is passed by reference. Inside the function, I can save somevar2 in a reference var, then later on assign a value to it via the pointer (if it's a string) by saying &arg2ref = 'abc'.
I'm guessing there's a way to do this in Delphi, either with a Variant as the oVar type, or using RTTI, or something else. I just haven't figured out the magic combination of pieces yet. (I just don't use pointers very often in Delphi.)
Maybe I need to save a raw pointer in oVar along with the type (say, oType), and cast a value through the pointer to save the property's value?
I'm hoping someone here might have some clear ideas.
BTW, I'm using Delphi XE3.
Use a pointer. It doesn't have to (and indeed shouldn't) be a "raw" pointer. Use a typed pointer, PValue. Pass in a PValue to your function, and then store that in oVal, which you should also declare a a PValue. Use # to create a pointer, and ^ to dereference.
I would not recommend passing arg2 by reference. Although you can still use # on it to get a pointer to the original variable passed to abc, the reference parameter disguises the fact that the variable needs to remain available indefinitely. Instead, declare arg2 as PValue so it's more obvious to the caller that indirection is involved.
// declaration
procedure abc(...; arg2: PValue);
// call
abc(..., #somevar2);
I want users of my C++ application to be able to provide anonymous functions to perform small chunks of work.
Small fragments like this would be ideal.
function(arg) return arg*5 end
Now I'd like to be able to write something as simple as this for my C code,
// Push the function onto the lua stack
lua_xxx(L, "function(arg) return arg*5 end" )
// Store it away for later
int reg_index = luaL_ref(L, LUA_REGISTRY_INDEX);
However I dont think lua_loadstring will do "the right thing".
Am I left with what feels to me like a horrible hack?
void push_lua_function_from_string( lua_State * L, std::string code )
{
// Wrap our string so that we can get something useful for luaL_loadstring
std::string wrapped_code = "return "+code;
luaL_loadstring(L, wrapped_code.c_str());
lua_pcall( L, 0, 1, 0 );
}
push_lua_function_from_string(L, "function(arg) return arg*5 end" );
int reg_index = luaL_ref(L, LUA_REGISTRY_INDEX);
Is there a better solution?
If you need access to parameters, the way you have written is correct. lua_loadstring returns a function that represents the chunk/code you are compiling. If you want to actually get a function back from the code, you have to return it. I also do this (in Lua) for little "expression evaluators", and I don't consider it a "horrible hack" :)
If you only need some callbacks, without any parameters, you can directly write the code and use the function returned by lua_tostring. You can even pass parameters to this chunk, it will be accessible as the ... expression. Then you can get the parameters as:
local arg1, arg2 = ...
-- rest of code
You decide what is better for you - "ugly code" inside your library codebase, or "ugly code" in your Lua functions.
Have a look at my ae. It caches functions from expressions so you can simply say ae_eval("a*x^2+b*x+c") and it'll only compile it once.