Re: need help to get bitoffsetof bitwidth for clang

2024-07-03 Thread Tim via Digitalmars-d-learn

On Tuesday, 2 July 2024 at 05:34:19 UTC, Dakota wrote:
I want to get `bitoffsetof` and `bitwidth` in clang, to verify 
the d memory layout.


I try this but not work:

```c
#define offsetof_bit(type, member) ((offsetof(type, member) * 
8) + __builtin_ctz(((type *)0)->member))

```


get this error:

```sh
cannot compute offset of bit-field 'field'
```


If you only want to see the layout, you can use the following 
command to dump it:

```
clang test.c -Xclang -fdump-record-layouts -c
```

File test.c could contain the following:
```
struct S
{
int a : 3;
int b : 29;
};
struct S dummy;
```

The above clang command would then output:
```
*** Dumping AST Record Layout
 0 | struct S
 0:0-2 |   int a
0:3-31 |   int b
   | [sizeof=4, align=4]
```

Inside a C/C++ program you could initialize a struct with all 
0xff, set one bitfield to zero and look at the bits. I have used 
this to compare the bitfield layout between D and C++ in a test 
added in https://github.com/dlang/dmd/pull/16590.


Re: Recommendations on porting Python to D

2024-04-24 Thread Tim via Digitalmars-d-learn

On Wednesday, 24 April 2024 at 19:50:45 UTC, Chris Piker wrote:
I have a somewhat extensive CGI based web service written in 
Python and I'd like to port it to D.  I can do this manually of 
course, and maybe that's the best way, but for a rough start, 
is anyone aware of any tools that generate an abstract syntax 
tree which could then be converted to somewhat equivalent D 
code?


My parser generator has an example with a grammar for Python: 
https://github.com/tim-dlang/dparsergen/tree/master/examples/python


Re: Threads

2023-03-22 Thread Tim via Digitalmars-d-learn

On Wednesday, 22 March 2023 at 07:16:43 UTC, Kagamin wrote:

static is thread local by default.

```
module main;
import app;
import core.thread;

int main(string[] args)
{
 static shared int result;
 static shared string[] args_copy;

 static void app_thread()
 {
 App app = new App();
 result = app.run(args_copy);
 }

 args_copy = cast(shared)args;

 // Running app interface in a thread;
 Thread thread = new Thread(_thread).start();
 thread.join();

 return result;
}
```


It seems work, but I have to change "int App.run(string[] args)" 
to "App.run(shared string[] args)" in app module and 
`std.getopt.getopt` throws me an error in the same module:


Error: none of the overloads of template `std.getopt.getopt` are 
callable using argument types `!()(shared(string[]), string, 
string, string*)`
/usr/include/dmd/phobos/std/getopt.d(420,14):Candidate 
is: `getopt(T...)(ref string[] args, T opts)`






Re: Threads

2023-03-22 Thread Tim via Digitalmars-d-learn

On Wednesday, 22 March 2023 at 07:16:43 UTC, Kagamin wrote:

static is thread local by default.

```
module main;
import app;
import core.thread;

int main(string[] args)
{
 static shared int result;
 static shared string[] args_copy;

 static void app_thread()
 {
 App app = new App();
 result = app.run(args_copy); // <-- Stucked here!
 }

 args_copy = cast(shared)args;

 // Running app interface in a thread;
 Thread thread = new Thread(_thread).start();
 thread.join();

 return result;
}
```


I've changed "int App.run(string[] args)" to "int App.run(shared 
string[] args)" in app module. Now I've got an error in 
std.getopt.getopt in the same module.


Error: none of the overloads of template `std.getopt.getopt` are 
callable using argument types `!()(shared(string[]), string, 
string, string*)`


Am I doing something wrong?



Threads

2023-03-21 Thread Tim via Digitalmars-d-learn
Hello! I am trying to make a simple multi-threading application. 
But I get an error when I run the main thread of the program in a 
thread. The question is: "How to pass arguments from the main 
thread to the newly created thread of itself". Here is a piece of 
code:


module main;
import app;
import core.thread;

int main(string[] args)
{

static int result;
static string[] args_copy;

static void app_thread()
{
App app = new App();
result = app.run(args_copy); //<-- Exception; static int 
App.run(string[] args)

//object.Exception@/usr/include/dmd/phobos/std/getopt.d(423):

// Invalid arguments string passed: program name missing
}

args_copy = args; //Why program name is missing while copy 
arguments?


// Running app interface in a thread;
Thread thread = new Thread(_thread).start();
thread.join();

return result;
}



Re: Structure initializer VS lambda function

2022-12-12 Thread Tim via Digitalmars-d-learn

On Monday, 12 December 2022 at 08:54:33 UTC, realhet wrote:

1. checking inside (on the first hierarchy level inside {})
   ,   => must be a struct initializer
   ;   => must be a lambda
   no , and no ;  => check it from the outside


Some statements don't end in a semicolon, so you would also need 
to check for those. For example:

```
auto lambda = { while(f()){} };
```

A lambda can also contain a comma expression:
```
auto lambda = { f(), g(); };
```


Re: Small structs: interfacing with C++ potentially broken

2021-12-20 Thread Tim via Digitalmars-d-learn

On Monday, 20 December 2021 at 10:24:00 UTC, Jan wrote:
Is this a known issue, or is there a way to instruct DMD to use 
a specific calling convention for a given type?


This looks like a bug. It seems to work without constructor in 
C++, but still crashes with a constructor in D. It also seems to 
work if a trivial destructor is added in D: ~this(){}


This could be related to POD types in C++. Structs with 
constructor or destructor are probably passed differently, but 
dmd only looks at the destructor.


Re: How to pass a class by (const) reference to C++

2021-12-16 Thread Tim via Digitalmars-d-learn

On Thursday, 16 December 2021 at 08:30:14 UTC, Jan wrote:
Ok, next problem. Maybe you know the necessary syntax for this 
one too.



C++
```cpp
class Test
{
public:
  __declspec(dllexport) static const int const_vars[2];
  __declspec(dllexport) static int nonconst_vars[2];
};

const int Test::const_vars[2] = {11, 23};
int Test::nonconst_vars[2] = {12, 24};
```

D
```cpp
extern(C++, class) struct Test
{
extern export static __gshared const(int)[2] const_vars;
extern export static __gshared int[2] nonconst_vars;
}
```

I get the nonconst_vars to link correctly, but for the 
const_vars the mangled name contains one less const than what 
MSVC generates, so I assume I have to wrap this somehow 
differently. I tried "const(int[2])" but that didn't make a 
difference.


D wants to link against:
`?const_vars@Test@@2PAHB`

which is:
`public: static int * const Test::const_vars" ()`

MSVC exports:
`?const_vars@Test@@2QBHB`

which is:
`public: static int const * const Test::const_vars`


Any idea?


That looks like another bug in the compiler. pragma(mangle, ...) 
should work as a workaround.


Re: How to pass a class by (const) reference to C++

2021-12-15 Thread Tim via Digitalmars-d-learn

On Wednesday, 15 December 2021 at 22:46:01 UTC, Jan wrote:
Btw. should I report this issue somewhere? Is far as I see this 
isn't logged yet:




Yes, it should be reported.


Re: How to pass a class by (const) reference to C++

2021-12-15 Thread Tim via Digitalmars-d-learn

On Wednesday, 15 December 2021 at 22:01:19 UTC, Jan wrote:

Ha, it works indeed!

```cpp
extern export __gshared static int var;
```

That's a declaration worthy of C++ ! Fewer keywords would be 
too usable :D


Joking aside, I understood the docs such that `__gshared` 
actually *is* `static` in D, no? Also why the `export` when 
it's an extern variable?


I agree that __gshared should imply static. That's probably a bug 
in the compiler.


Using `extern` without `export` would only work with static 
linking (on Windows). `export` without `extern` would be 
exporting the variable for others, like `__declspec(dllexport)` 
in C++. `export` and `extern` combined imports the variable, like 
`__declspec(dllimport)`.


Re: How to pass a class by (const) reference to C++

2021-12-15 Thread Tim via Digitalmars-d-learn

On Wednesday, 15 December 2021 at 19:28:44 UTC, Jan wrote:

C++
```cpp
class Test
{
public:
  __declspec(dllexport) static int var;
};

int Test::var = 42;
```

D
```cpp
extern(C++, class) struct Test
{
  extern (C++) export extern __gshared int var;
}
```

(also tried without the duplicate extern(C++) and without 
'export')


DLL compiled with Visual Studio 2019. D DLL compiled with a 3 
day old nightly build of DMD.


DMD says:
`error LNK2019: unresolved external symbol "public: static int 
Test::var" (?var@Test@@2HA)`


I've checked the .exp file of the DLL where the symbol is 
defined in, and it has the exact same name there. And yes, I 
correctly link against that DLL in general, other symbols 
located in that DLL are linked just fine by DMD.


I can reproduce your problem. It seems to work if var is 
additionally static:


extern(C++, class) struct Test
{
   extern (C++) export extern static __gshared int var;
}

It's probably a bug, that it does not work without static. The 
documentation says "__gshared may also be applied to member 
variables and local variables. In these cases, __gshared is 
equivalent to static, except that the variable is shared by all 
threads rather than being thread local." 
(https://dlang.org/spec/attribute.html#gshared)




Re: How to pass a class by (const) reference to C++

2021-12-15 Thread Tim via Digitalmars-d-learn

On Wednesday, 15 December 2021 at 15:20:18 UTC, Jan wrote:
As I was told linking against functions in DLLs works 
perfectly, because it is identical to static linking. Linking 
against global/static variables supposedly differs and that's 
not handled correctly for DLLs. As I said, I talked to someone 
who worked on fixing lots of those issues a while ago and he 
immediately knew about this limitation.


I have used global variables from DLLs successfully. DMD now also 
has a test for C++ DLLs: 
https://github.com/dlang/dmd/blob/master/test/dshell/extra-files/dll_cxx/testdll.d


The variable should be declared like this in C++:
__declspec(dllexport) int value;

It can then be accessed from D with this:
extern (C++) export extern __gshared int value;

Do you have a test case for your problem?


Re: How to pass a class by (const) reference to C++

2021-12-13 Thread Tim via Digitalmars-d-learn

On Monday, 13 December 2021 at 21:17:49 UTC, Jan wrote:
Unfortunately no. Maybe the cast would even make it work, but I 
can't have "A" and "_A" in D as separate types, because the 
class is supposed to link to C++ functions and thus renaming it 
from A to _A breaks that. On the other hand I can't give the 
struct another name either, because that's how it is linked to 
in "CppFunc".


The easiest workaround is probably to set the mangling manually:

pragma(mangle, "_Z7CppFuncRK1A")
extern(C++) void CppFunc(const A arg);

This mangling is for the Itanium ABI, which is used by Linux and 
other operating systems. It needs to be different for Windows.


Re: How to pass a class by (const) reference to C++

2021-12-13 Thread Tim via Digitalmars-d-learn

On Monday, 13 December 2021 at 15:21:19 UTC, Jan wrote:
On Monday, 13 December 2021 at 13:02:50 UTC, Ola Fosheim 
Grøstad wrote:
Yes, I wouldn't want to use it, maybe manual mangling is 
better, but still painful. ```const A&``` is so common in C++ 
API's that it really should be supported out-of-the-box.  All 
it takes is adding a deref-type-constructor to the D language 
spec, e.g. ```ref const(@deref(A))```


I fully agree. This pattern is so common in C++, that I am 
surprised D doesn't have a way to do this already. The whole 
idea of linking against C++ is to interop easily, with little 
friction and high performance. Needing to build any shims or 
redesign the C++ side is very much contrary to this goal.


Does anyone know whether such issues have been discussed 
before? I can't imagine I'm the first one to run into this.


A similar issue about tail const classes has already been 
discussed:

https://digitalmars.com/d/archives/digitalmars/D/const_Class_is_mangled_as_Class_const_const_299139.html

I made a pull request, which changes the mangling to tail const 
for classes passed directly as parameter or return type, but now 
think this would break too much code: 
https://github.com/dlang/dmd/pull/13369
The proposal to add a deref-type-constructor, would also allow to 
have tail const classes.


Re: How to use inheritance when interfacing with C++ classes?

2021-12-10 Thread Tim via Digitalmars-d-learn

On Friday, 10 December 2021 at 12:46:07 UTC, rempas wrote:

On Thursday, 9 December 2021 at 21:35:14 UTC, Tim wrote:
Methods, which are not virtual in C++, also have to be marked 
final in D, because C++ and D use a different default.


Is this a must or just good practices?


All virtual methods have to match exactly including order. If a 
virtual method is missing or added, then calling this or a later 
virtual method could call the wrong method or generate a 
segmentation fault. Non-virtual methods have to be marked final 
in D, but can also be removed.


Re: How to use inheritance when interfacing with C++ classes?

2021-12-09 Thread Tim via Digitalmars-d-learn

On Thursday, 9 December 2021 at 19:05:08 UTC, rempas wrote:

Anyone has an idea?


The referenced methods like Fl_Widget::_clear_fullscreen are 
implemented directly in the header, so the D code also needs the 
implementation, because it is not included in the compiled 
library.


Methods, which are not virtual in C++, also have to be marked 
final in D, because C++ and D use a different default.


Re: Is there an alternative to "__FUNCTION__" that gives the actual function symbol and not the name as a string?

2021-10-23 Thread Tim via Digitalmars-d-learn

On Saturday, 23 October 2021 at 19:52:19 UTC, Simon wrote:


Thanks for putting up with me! I tried a bunch and it seems 
like I left out too much code, because I can't get it working 
100%. I didn't even know about the q{} syntax, so I didn't 
think the stuff I left out would matter, but when using this 
approach it apparently does. I am going to show the full code 
here, just so that there are no more suprises.


Sorry for this becoming a "please do my homework" kind of 
question. I tried for half an hour with no idea how to fix the 
errors I'm seeing. Something always fails.


The full implementation of OUTPUT_REPRO_CASE looked like this:


enum MAKE_FUNCTION_REPRODUCIBLE(alias func, s64 
execution_count_to_log_reproduction_on = -1) =

  "static s64 execution_count = 0;
  
if(context.settings.debug_.output_call_counts_for_reproducible_functions)
dlog(\""~fullyQualifiedName!func~" call count: %lld\", 
execution_count);


  if(execution_count == 
"~execution_count_to_log_reproduction_on.stringof~"){

dlog(generate_reproduction_for_current_function_call!(
  "~fullyQualifiedName!func~",
  
["~get_string_argument_list_of_function!([ParameterIdentifierTuple!func])~"])(

  context.temp_allocator,
  
"~get_argument_list_of_function!([ParameterIdentifierTuple!func])~"));


  trigger_breakpoint();
}";

It calls the function

String generate_reproduction_for_current_function_call(alias 
func, string[] parameter_names, Parameter_Types...)(Allocator* 
allocator, Parameter_Types parameters);


that actually creates the code-string. I did a lot of trial and 
error getting the trait-calls to expand at the right time 
(become part of the mixin string or outside of it) and falling 
on my nose about when something is a type vs a string and so 
on, so this became really ugly. If you have a better suggestion 
I'm open to it.


I was testing this inside the function

Dynamic_Array!(Polygon) clip_polygons(Slice!Vector2 p0, 
Slice!Vector2 p1, bool return_difference_instead_of_union = 
true, Slice!(Slice!Vector2) p0_holes = Slice!(Slice!Vector2)(), 
bool debug_print = false);


in which the OUTPUT_REPRO_CASE expands to:

static s64 execution_count = 0;
  
if(context.settings.debug_.output_call_counts_for_reproducible_functions)

dlog("vbl.clip_polygons call count: %lld", execution_count);

  if(execution_count == -1L){
dlog(generate_reproduction_for_current_function_call!(
  vbl.clip_polygons,
  ["p0", "p1", "return_difference_instead_of_union", 
"p0_holes", "debug_print"])(

  context.temp_allocator,
  p0, p1, return_difference_instead_of_union, p0_holes, 
debug_print));


  trigger_breakpoint();
}

When I try to change the whole thing to be a token string, 
execution_count_to_log_reproduction_on was suddenly undefined. 
I changed this to be an abominational mix of token string and 
string literal and then it sort of worked, except then the 
whole business of making the parameter names expand as actual 
tokens and not strings failed for some reason.


I am super confused (this is a reccuring theme with D compile 
time stuff on my part :/). Can you show me how this can work 
with your token string solution?


Maybe you need another mixin in the mixin. The first mixin gets 
the symbol to the current function. Information from the symbol 
is used to generate the second mixin. It could be done like this:


import std.traits, std.stdio;
string generateLogCode(alias func)()
{
string code = "writeln(";
code ~= "\"" ~ fullyQualifiedName!func ~ "(\"";
foreach(i, param; ParameterIdentifierTuple!func)
{
if(i)
code ~= ", \", \"";
code ~= ", " ~ param;
}
code ~= ", \");\");";
return code;
}
enum OUTPUT_REPRO_CASE = q{
pragma(msg, generateLogCode!(__traits(parent, {}))());
mixin(generateLogCode!(__traits(parent, {}))());
};
void test(int a, int[] b)
{
mixin(OUTPUT_REPRO_CASE);
}
void main()
{
test(1, [2, 3]);
}


Re: Is there an alternative to "__FUNCTION__" that gives the actual function symbol and not the name as a string?

2021-10-23 Thread Tim via Digitalmars-d-learn

On Saturday, 23 October 2021 at 18:56:48 UTC, Simon wrote:

And I tried to use your suggestion like this:

enum OUTPUT_REPRO_CASE(alias func = __traits(parent, {})) = 
"build the actual code stuff with"~fullyQualifiedName!func~" 
and so on";


Which doesn't work. In that case func seems to become the 
parent namespace. If I substitute fullyQualifiedName!func with 
fullyQualifiedName!(__traits(parent, {}))) I get a circular 
dependecy error.


How do I have to use this exactly?


This seems to work:

import std.traits, std.stdio;
enum OUTPUT_REPRO_CASE = q{
string name = fullyQualifiedName!(__traits(parent, {}));
writeln(name);
};
void test()
{
mixin(OUTPUT_REPRO_CASE);
}
void main()
{
test();
}



Re: Is there an alternative to "__FUNCTION__" that gives the actual function symbol and not the name as a string?

2021-10-23 Thread Tim via Digitalmars-d-learn

On Saturday, 23 October 2021 at 18:23:47 UTC, Simon wrote:
So what I am looking for then is the equivalent to __FUNCTION__ 
that evaluates to the actual symbol of the function instead of 
its name, so it can be used as a parameter to 
ParameterIdentifierTuple.


You could use the following:

alias F = __traits(parent, {});

The lambda {} is a symbol inside the function. F will be its 
parent, which is the function itself.


Re: Better debugging?

2021-10-03 Thread Tim via Digitalmars-d-learn

On Sunday, 3 October 2021 at 22:26:15 UTC, Imperatorn wrote:

On Sunday, 3 October 2021 at 22:21:45 UTC, Tim wrote:

[...]


You don't say which operating system you are using.
I usually use Visual D which works great imo.

If I use vscode I use the C++ debug extension (don't remember 
what it's called).


If I debug outside of the IDE I use WinDbg, also has source 
debug support if configured correctly.


If you are on Linux I'm not sure, but I would go for the C++ 
thing probably.


Apologies. I use KDE linux


Better debugging?

2021-10-03 Thread Tim via Digitalmars-d-learn

Hi all,

I am currently using GDB within VScode with the -gc DMD2 compiler 
switch and my debugging is not amazing. Whenever I inspect a 
struct/object it just shows me the pointer rather than the object 
information and strings come up as a gross array of the 
characters. Does anybody happen to know whether LDB is better or 
how I can have a nicer debug environment?


Thanks in advance


Re: Understanding range.dropBackOne

2021-09-28 Thread Tim via Digitalmars-d-learn

On Tuesday, 28 September 2021 at 23:12:14 UTC, Adam Ruppe wrote:

On Tuesday, 28 September 2021 at 22:56:17 UTC, Tim wrote:

[...]


Note that this array has a fixed size.


[...]


Here the window[] takes a variable-length slice of it. Turning 
it from int[25] into plain int[]. Then you can drop one since 
it is variable length. Then appending again ok cuz it is 
variable. Then the window assign just copies it out of the 
newly allocated variable back into the static length array.



[...]


But over here you are trying to use the static array directly 
which again has fixed length, so it is impossible to cut an 
item off it or add another to it.



[...]


It takes a slice of the static array - fetching the pointer and 
length into runtime variables.


Perfect answer. Thanks for clearing that all up mate


Understanding range.dropBackOne

2021-09-28 Thread Tim via Digitalmars-d-learn

I'm doing the following:

```D
int[25] window = 0;

// Later in a loop
window = someInteger ~ window[].dropBackOne;
```

But I'm struggling to understand why the following doesn't work
```D
window = someInteger ~ window.dropBackOne;
```

What does the `[]` do exactly? Is an array not a bidirectional 
range?


Re: Issue with small floating point numbers

2021-05-12 Thread Tim via Digitalmars-d-learn

On Thursday, 13 May 2021 at 03:46:28 UTC, Alain De Vos wrote:

Not is is not wrong it is wright.
Because you use not pi but an approximation of pi the result is 
not zero but an approximation of zero.


Oh, of course. Jesus that sucks big time. Any idea on how to use 
assert with an approximate number like this?


Issue with small floating point numbers

2021-05-12 Thread Tim via Digitalmars-d-learn

Hello all,

I have this piece of code
```D
/**
Rotate a 2D array (Vector) by phi radians

Params:
vec = 2D Vector to rotate
phi = Degree with which to rotate the Vector in radians

Returns:
Rotated 2D array (Vector)

Example:

*/
pragma(inline, true)
Point2 rotate2D(in Point2 vec, in float phi) pure nothrow {
double x = (vec[0]*cos(phi)) - (vec[1]*sin(phi));
double y = (vec[0]*sin(phi)) + (vec[1]*cos(phi));
return [x, y];
}

unittest{
auto p = rotate2D([0.0, 10.0], PI_2);
assert(p == [-10.0, 0.0]);
}
```

When I run the unittest, I get ```[-10, -4.37114e-07]``` back, 
which is obviously wrong. Any idea as to why it's not making the 
y-axis zero? Is it a rounding issue with the types I'm using?


Thanks in advance


Re: Shutdown signals

2021-05-11 Thread Tim via Digitalmars-d-learn

On Tuesday, 11 May 2021 at 06:59:10 UTC, Patrick Schluter wrote:

On Tuesday, 11 May 2021 at 06:44:57 UTC, Tim wrote:

On Monday, 10 May 2021 at 23:55:18 UTC, Adam D. Ruppe wrote:

[...]


I don't know why I didn't find that. I was searching for the 
full name, maybe too specific? Thanks anyways, this is super 
helpful. I wish it was documented better though :(


So why use sigaction and not signal? From what I can tell 
signal is the C way of doing things


Use `sigaction()`, `signal()` has problems. See this 
stackoverflow [1] question explains the details


[1]: 
https://stackoverflow.com/questions/231912/what-is-the-difference-between-sigaction-and-signal


Thanks a lot!


Re: Shutdown signals

2021-05-11 Thread Tim via Digitalmars-d-learn

On Monday, 10 May 2021 at 23:55:18 UTC, Adam D. Ruppe wrote:

On Monday, 10 May 2021 at 23:35:06 UTC, Tim wrote:

[...]


dpldocs.info/signal it comes up as the second result.

The C function you call from there (on linux anyway) is 
sigaction. A little copy/paste out of my terminal.d:


```d
  // I check this flag in my loop to see if an interruption 
happened

  // then i can cleanly exit from there.
   __gshared bool interrupted;

  // the interrupt handler just sets the flag
   extern(C)
   void interruptSignalHandler(int sigNumber) nothrow {
   interrupted = true;
   }

   // then this code registers the handler with the system
   import core.sys.posix.signal;
   sigaction_t n;
   n.sa_handler = 
   sigaction(SIGINT, , ); // third arg can 
also be null if you don't care about the old one

```


I don't know why I didn't find that. I was searching for the full 
name, maybe too specific? Thanks anyways, this is super helpful. 
I wish it was documented better though :(


So why use sigaction and not signal? From what I can tell signal 
is the C way of doing things


Re: Shutdown signals

2021-05-10 Thread Tim via Digitalmars-d-learn

On Monday, 10 May 2021 at 23:31:11 UTC, Adam D. Ruppe wrote:

On Monday, 10 May 2021 at 23:20:47 UTC, Tim wrote:

Hi all,

How can I get a D program to detect something a keyboard 
interrupt so I shut things down in a specific way?


import core.sys.posix.signal; then you can use the same 
functions as C to set signal handlers.


I can't find that in the docs, nor in dpldocs. Can you help out 
with this?


Shutdown signals

2021-05-10 Thread Tim via Digitalmars-d-learn

Hi all,

How can I get a D program to detect something a keyboard 
interrupt so I shut things down in a specific way?


Re: Is there an easy way to convert a C header to a D module?

2021-03-14 Thread Tim via Digitalmars-d-learn

On Monday, 15 March 2021 at 02:47:12 UTC, Adam D. Ruppe wrote:

On Monday, 15 March 2021 at 02:43:01 UTC, Tim wrote:

Seems pretty good. Does it work on c++ stuff too?


I don't think so


Bother. Well, I'm sure it will still be useful though. Thanks for 
the heads up


Re: Is there an easy way to convert a C header to a D module?

2021-03-14 Thread Tim via Digitalmars-d-learn

On Monday, 15 March 2021 at 02:03:09 UTC, Adam D. Ruppe wrote:

On Monday, 15 March 2021 at 01:53:31 UTC, Tim wrote:
I'm needing to use a c/c++ library in a D program and I'm 
struggling with creating a binding as it seems like an 
enormous amount of regex modifications. Is there an existing 
program that can create most if not all of a binding for me?


https://github.com/jacob-carlborg/dstep

That does most of it, then you fix it up with some regex or 
whatever to finish the job.


Seems pretty good. Does it work on c++ stuff too?


Is there an easy way to convert a C header to a D module?

2021-03-14 Thread Tim via Digitalmars-d-learn
I'm needing to use a c/c++ library in a D program and I'm 
struggling with creating a binding as it seems like an enormous 
amount of regex modifications. Is there an existing program that 
can create most if not all of a binding for me?


Thanks


Vibe.d diet template help

2021-02-06 Thread Tim via Digitalmars-d-learn

Hi all,

I'm trying to render a diet template out to a WebSocket as a 
string to be inserted into a specific portion of the currently 
served page. Does anyone know how to go about this?


How can I stop D from dropping decimals in strings

2021-02-02 Thread Tim via Digitalmars-d-learn

Hi all,

I have to serialize an array like [0.0, 0.0, 0.0] to a Json 
object. During this process, the serializer creates a string of 
the array, but it creates "[0, 0, 0]", dropping the decimal. How 
can I stop this?


Re: How can I use UFCS for a loop

2021-01-25 Thread Tim via Digitalmars-d-learn

On Tuesday, 26 January 2021 at 01:38:45 UTC, Q. Schroll wrote:

On Tuesday, 26 January 2021 at 00:47:09 UTC, Tim wrote:

Hi all,

How can I change the following to a more D-like approach by 
using UFCS?



double[3] result;


Unless you have a good reason, use a slice and not a static 
array:


double[] result;

The result of std.array.array will be a slice anyway.


Why would I need to use a slice instead of a static array? I'm 
using a static array in this instance because I have and 
underlying 3d vector with double[3] as its base type


How can I use UFCS for a loop

2021-01-25 Thread Tim via Digitalmars-d-learn

Hi all,

How can I change the following to a more D-like approach by using 
UFCS?



double[3] result;
Json json = res.readJson;
for(int i = 0; i < json.length; i++){
result[i] = json[i].to!double;
}


I'd prefer to do something like:


result = res.readJson[].map!(to!double);


Re: Issue with socket recieve

2021-01-20 Thread Tim via Digitalmars-d-learn

On Thursday, 21 January 2021 at 03:35:05 UTC, Adam D. Ruppe wrote:

On Thursday, 21 January 2021 at 03:24:13 UTC, Tim wrote:

No, I don't. It should be all garbage collected right?


Yeah, but that's where the problem comes.

Note that by destructor, I mean *any* function in your code 
called `~this() {}`. If there are any and they call a memory 
allocation function, that's how you get the 
InvalidMemoryOperationError.


I'd have to look up if there's any other causes of that...


I am aware of this, there is absolutely no ~this in *my* code


Re: Issue with socket recieve

2021-01-20 Thread Tim via Digitalmars-d-learn

On Thursday, 21 January 2021 at 03:21:41 UTC, Adam D. Ruppe wrote:

On Wednesday, 20 January 2021 at 21:31:54 UTC, Tim wrote:
Unable to open 'recv.c': Unable to read file 
'/build/glibc-ZN95T4/glibc-2.31/sysdeps/unix/sysv/linux/recv.c' (Error: Unable to resolve non-existing file '/build/glibc-ZN95T4/glibc-2.31/sysdeps/unix/sysv/linux/recv.c').

[snip]
generate a core.exception.InvalidMemoryOperationError that I 
can't catch.



None of this makes much sense given the code you provided. 
InvalidMemoryOperationError (the scariest thing in D btw, such 
a pain to debug) is usually caused by a class destructor 
somewhere, and none of those should be trying to resolve those 
files.


Do you have any destructors defined?


You seem like a rather switched-on fellow. Would you be able to 
send me an email at some point at tim.oli...@tutanota.com. I have 
a proposition for you.


Re: Issue with socket recieve

2021-01-20 Thread Tim via Digitalmars-d-learn

On Thursday, 21 January 2021 at 03:21:41 UTC, Adam D. Ruppe wrote:

On Wednesday, 20 January 2021 at 21:31:54 UTC, Tim wrote:
Unable to open 'recv.c': Unable to read file 
'/build/glibc-ZN95T4/glibc-2.31/sysdeps/unix/sysv/linux/recv.c' (Error: Unable to resolve non-existing file '/build/glibc-ZN95T4/glibc-2.31/sysdeps/unix/sysv/linux/recv.c').

[snip]
generate a core.exception.InvalidMemoryOperationError that I 
can't catch.



None of this makes much sense given the code you provided. 
InvalidMemoryOperationError (the scariest thing in D btw, such 
a pain to debug) is usually caused by a class destructor 
somewhere, and none of those should be trying to resolve those 
files.


Do you have any destructors defined?


No, I don't. It should be all garbage collected right?

Hahahaha, about 50% of my troubles are 
InvalidMemoryOperationError! It's so frustrating. This whole 
project has been a nightmare


Re: Exit code -4

2021-01-20 Thread Tim via Digitalmars-d-learn

On Thursday, 21 January 2021 at 01:07:22 UTC, Paul Backus wrote:

On Thursday, 21 January 2021 at 00:49:26 UTC, Tim wrote:


Oh, so it's just signal 4, not -4?


The signal is 4. The exit status is -4.

https://en.wikipedia.org/wiki/Signal_(IPC)#POSIX_signals
https://en.wikipedia.org/wiki/Exit_status#POSIX


Those lines were super useful! Not sure why I couldn't find that 
info on my own ...


Re: Exit code -4

2021-01-20 Thread Tim via Digitalmars-d-learn

On Thursday, 21 January 2021 at 00:47:36 UTC, Adam D. Ruppe wrote:

On Thursday, 21 January 2021 at 00:37:19 UTC, Tim wrote:

Hi all,

From time to time my program crashes with exit code -4. I 
can't seem to find much on the code. Does anyone know what 
this means and how to debug the issue?


Unix signal #4 is illegal instruction (negative returns usually 
mean it was killed by that number signal). Most common way to 
hit that is a broken function pointer or corrupted class 
leading into data that isn't supposed to be executed as code. 
Also possible an assert(0) got hit in release mode or something 
like that.


Easiest way to debug it is to open it in a debugger and look at 
the stack trace to see where it came from.


Oh, so it's just signal 4, not -4?


Exit code -4

2021-01-20 Thread Tim via Digitalmars-d-learn

Hi all,

From time to time my program crashes with exit code -4. I can't 
seem to find much on the code. Does anyone know what this means 
and how to debug the issue?


Issue with socket recieve

2021-01-20 Thread Tim via Digitalmars-d-learn

Hi all,

I'm having a really terrible bug that seemed to come from nowhere 
and is really hard to narrow down. I have a threaded message 
service that works via local TcpSocket. Every time I run it, 
either an error saying:
Unable to open 'recv.c': Unable to read file 
'/build/glibc-ZN95T4/glibc-2.31/sysdeps/unix/sysv/linux/recv.c' 
(Error: Unable to resolve non-existing file 
'/build/glibc-ZN95T4/glibc-2.31/sysdeps/unix/sysv/linux/recv.c').
when socket.receive() is called. Sometimes I get the same thing 
but for socket.accept() instead (different file). This seems to 
generate a core.exception.InvalidMemoryOperationError that I 
can't catch.


Yesterday, this came up after a couple of minutes of the program 
running, now it happens straight away. I haven't touched this 
class in a week or so and can't think of why all of a sudden it 
has come up with this issue. Code dump below


-



module message_service;

import std.stdio;
import std.socket;
import core.thread;


/**
Threaded socket manager to serve inter-service communication

Calls delegates when the appropriate command is received
*/
class MessageService : Thread{
   /// The socket over which communication is possible
   private Socket server;
   /// The connection to the client that sends commands
   private Socket client;
   /// Associative array of command strings and relative 
functions to call

   private void delegate()[string] commands;
   /// Global buffer. Holds the command being recieved
   private char[1024] buffer = 0;


   ///
   this(ushort port, void delegate()[string] _commands){
   commands = _commands;
   server = new TcpSocket();
   server.setOption(SocketOptionLevel.SOCKET, 
SocketOption.REUSEADDR, true);

   server.bind(new InternetAddress(port));
   writefln("Message service started on port %d", port);
   super();
   start();
   }


   /// Loops over polling the client socket for commands
   void mainLoop(){
   while(true){
   pollMessages();
   }
   }


   /**
   Polls the client socket for characters to build up the 
message buffer


   When a string command is found, it calls the appropriate 
function

   */
   void pollMessages(){
   server.listen(1);
   if(client is null) client = server.accept();

   // Add to the message buffer
   auto buffLength = client.receive(buffer);

   if(buffLength){
   auto message = cast(string) buffer[0 .. buffLength];

   foreach(cmd; commands.byKey){
   if(cmd == message){
   // Reset the message buffer
   buffer = 0;
   commands[cmd]();
   return;
   }
   }
   }
   }
}


Re: Generating documentation help

2021-01-19 Thread Tim via Digitalmars-d-learn
On Wednesday, 20 January 2021 at 01:25:28 UTC, Adam D. Ruppe 
wrote:

On Wednesday, 20 January 2021 at 01:00:32 UTC, Tim wrote:
But if I deleted index.html then reran the doc gen, it worked 
just fine. Looks like index.html is not being updated


oh yeah i forgot i did that cuz I so often build 
individual files and it deleting the index annoyed me


oops, i should prolly make that a command line arg or something.

so yeah my error but now we know.


Glad we worked it out


Re: Generating documentation help

2021-01-19 Thread Tim via Digitalmars-d-learn
On Wednesday, 20 January 2021 at 00:53:54 UTC, Adam D. Ruppe 
wrote:

On Wednesday, 20 January 2021 at 00:16:51 UTC, Tim wrote:
They are defined "module simulator" and "module analyzer". I 
also have "module math" etc. that are added to the index


That's weird...

There are a bunch of command line args to adrdox that might 
help like


--document-undocumented
--write-private-docs
--write-internal-modules

(see --help for more info)

but by the sounds of it none of those should apply to you. 
idk...


None of those worked. But if I deleted index.html then reran the 
doc gen, it worked just fine. Looks like index.html is not being 
updated


Re: Generating documentation help

2021-01-19 Thread Tim via Digitalmars-d-learn
On Wednesday, 20 January 2021 at 00:13:42 UTC, Adam D. Ruppe 
wrote:

On Wednesday, 20 January 2021 at 00:06:35 UTC, Tim wrote:

Yeah, they have both. They also contain the main entrypoint


What are the module names? If it is like `module foo.main;` it 
will be listed under `foo` as a submodule rather than top-level 
since it is all organized by name.


(if the code is public just send a link plz and I'll take a 
look there)


Unfortunately, the code isn't public. They are defined "module 
simulator" and "module analyzer". I also have "module math" etc. 
that are added to the index, just not simulator and analyzer 
(which both have the main entrypoint)


Re: Generating documentation help

2021-01-19 Thread Tim via Digitalmars-d-learn
On Wednesday, 20 January 2021 at 00:03:16 UTC, Adam D. Ruppe 
wrote:

On Tuesday, 19 January 2021 at 23:58:59 UTC, Tim wrote:
The main issue is that those scripts aren't being added to 
index.html


Do they have module definitions and doc comments in there 
somewhere?


like here I have all kinds of things 
http://dpldocs.info/experimental-docs/index.html


Yeah, they have both. They also contain the main entrypoint


Re: Generating documentation help

2021-01-19 Thread Tim via Digitalmars-d-learn

On Tuesday, 19 January 2021 at 23:57:21 UTC, Adam D. Ruppe wrote:

On Tuesday, 19 January 2021 at 23:51:00 UTC, Tim wrote:
I'm creating a u-services based app so my apps need to be 
documented properly as well. I can get around this by defining 
them as modules but then adrdox doesn't add them to index.html


Well, it does all .d files passed in directories given to it 
that have a module declaration. (And all .d files should have a 
module declaration anyway btw.)


If they live in different places, you can pass that too like

dub run adrdox -- . ../whatever-else


The main issue is that those scripts aren't being added to 
index.html


Re: Generating documentation help

2021-01-19 Thread Tim via Digitalmars-d-learn

On Sunday, 17 January 2021 at 22:27:13 UTC, Adam D. Ruppe wrote:

On Sunday, 17 January 2021 at 21:48:20 UTC, Paul Backus wrote:

I recommend using adrdox instead:


note you should be able to just

dub run adrdox

and it will spit out `generated_docs/files...`

(assuming i haven't broken that recently)


This is really amazing! However, it only lays out the 
documentation for modules that are being imported (useful for 
documenting libraries). I'm creating a u-services based app so my 
apps need to be documented properly as well. I can get around 
this by defining them as modules but then adrdox doesn't add them 
to index.html


Re: How can I check to see if template type is an array?

2021-01-19 Thread Tim via Digitalmars-d-learn

On Tuesday, 19 January 2021 at 22:45:19 UTC, Paul Backus wrote:

On Tuesday, 19 January 2021 at 22:38:41 UTC, Tim wrote:

On Tuesday, 19 January 2021 at 22:36:47 UTC, Paul Backus wrote:

On Tuesday, 19 January 2021 at 22:34:04 UTC, Tim wrote:
On Tuesday, 19 January 2021 at 22:31:47 UTC, Paul Backus 
wrote:
You've almost got it. The correct syntax is `is(T == U[], 
U)`. You can read it as "there exists some type U such that 
T == U[]".


Thanks! Do I need to specify U in the template function?


No, only inside the is(...) expression.


What if it is a static array i.e. double[3]?


is(T == U[n], U, size_t n)


Easy, thanks a lot!


Re: How can I check to see if template type is an array?

2021-01-19 Thread Tim via Digitalmars-d-learn

On Tuesday, 19 January 2021 at 22:36:47 UTC, Paul Backus wrote:

On Tuesday, 19 January 2021 at 22:34:04 UTC, Tim wrote:

On Tuesday, 19 January 2021 at 22:31:47 UTC, Paul Backus wrote:
You've almost got it. The correct syntax is `is(T == U[], 
U)`. You can read it as "there exists some type U such that T 
== U[]".


Thanks! Do I need to specify U in the template function?


No, only inside the is(...) expression.


What if it is a static array i.e. double[3]?


Re: How can I check to see if template type is an array?

2021-01-19 Thread Tim via Digitalmars-d-learn

On Tuesday, 19 January 2021 at 22:31:47 UTC, Paul Backus wrote:
You've almost got it. The correct syntax is `is(T == U[], U)`. 
You can read it as "there exists some type U such that T == 
U[]".


Thanks! Do I need to specify U in the template function?


How can I check to see if template type is an array?

2021-01-19 Thread Tim via Digitalmars-d-learn

Hi all,

I need to be able to check in a template whether the type given 
is an array type so that I can do some different logic. How can I 
do this? I would have thought that if(is(T == [])) would work, 
but no.



Thanks in advance


Generating documentation help

2021-01-17 Thread Tim via Digitalmars-d-learn

Hi there,

I have a couple of (probably) fairly simple questions. First, 
when I generate documentation files (-Dd docs) for my project, it 
also generates documentation for the library Mir. How can I fix 
the compiler pulling in those docs as well?


It seems that D won't let me document class constructors. This is 
a problem as I'd like to be able to document the constructor 
parameters. If I put the class documentation above the class 
definition, then ddoc gives an error that the parameters 
specified can't be found.



Thanks


Re: How to define delegate with needed parameters

2021-01-13 Thread Tim via Digitalmars-d-learn

On Thursday, 14 January 2021 at 00:29:23 UTC, Paul Backus wrote:

Easiest way is to use a lambda:

doSomething(() => foo(q))


This worked perfectly, thank you for your timely response~


How to define delegate with needed parameters

2021-01-13 Thread Tim via Digitalmars-d-learn
I would like to be able to create a delegate but also supply the 
function parameters to be used for the function call. How can I 
go about doing this? Example:


void foo(int i){
}

void bar(string m){
}

doSomething((q));
doSomething(("test");


Re: Member variables in method are null when called as delegate from thread

2021-01-12 Thread Tim via Digitalmars-d-learn

On Tuesday, 12 January 2021 at 01:49:11 UTC, tsbockman wrote:
The compiler and the physical CPU are both allowed to change 
the order in which instructions are executed to something 
different from what your code specifies, as long as the 
visible, "official" results and effects of the chosen order of 
execution are the same as those of your specified code, FROM 
THE PERSPECTIVE OF THE EXECUTING THREAD.


This is allowed so that the compiler can optimize to minimize 
negative "unofficial" effects such as the passage of time and 
memory consumption.


However, this re-ordering IS permitted to freely alter the 
behavior of your code from the perspective of OTHER threads. A 
likely cause of your bug is that the write to db by the 
constructor's thread is being committed to memory after the 
read of db by the MessageService thread.


In order to RELIABLY fix this kind of problem, you must 
correctly use the only commands which the compiler and CPU are 
NOT allowed to reorder with respect to other threads, namely 
atomic operations, memory barriers and synchronization 
primitives. A wide selection of these tools may be found in 
these D runtime library modules:


core.sync: 
http://dpldocs.info/experimental-docs/core.sync.html
core.atomic: 
http://dpldocs.info/experimental-docs/core.atomic.html
core.thread: 
http://dpldocs.info/experimental-docs/core.thread.html


(I recommend using Adam D. Ruppe's unofficial but superior 
rendering of the D runtime documentation at dpldocs.info rather 
than the official dlang.org rendering, as I found some 
necessary pieces of the documentation are just mysteriously 
missing from the offical version.)


Be warned that most models of multi-threaded programming are 
difficult to implement correctly, as opposed to ALMOST 
correctly with subtle heisen-bugs. You should either stick to 
one of the known simple models like immutable message passing 
with GC, or do some studying before writing too much code.


Here are some resources which I have found very helpful in 
learning to understand this topic, and to avoid its pitfalls:


Short educational game: https://deadlockempire.github.io/
Tech talk by C++ expert Herb Sutter (D's core.atomic uses 
the C++ memory model):

https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-of-2

https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-2-of-2


If you want to seriously dig into this, I suggest reviewing 
some or all of the content at the links above. If you're still 
confused about how to apply it in D, feel free to come back and 
ask for examples or code reviews. I'd rather not start with 
examples, though, because if you don't understand the rules and 
principles behind them, it's really easy to unknowingly 
introduce bugs into otherwise correct examples with seemingly 
innocent changes.


Fantastic response, thank you! I did some more digging and 
properly narrowed down where the issue is and created a test 
script that demonstrates the problem. Let me know what you think 
and if it could still be a similar problem to what you have 
stated above. I'll still read that info you sent to sharpen up on 
these concepts.


Basically, the program calls a function which modifies a document 
in the database. If it is called form it's own class' 
constructor, it works fine. If it is called by a thread, it never 
returns. I don't think that a member variable is going null or 
anything. But a strange problem that I can't seem to debug. The 
output is at the bottom.




import vibe.db.mongo.mongo;
import core.thread;
import std.stdio;

void main(){
auto callable = new Callable();

while(true){}
}

class Caller : Thread{
void delegate() mFunc;

this(void delegate() func){
mFunc = func;
super();
start();
}

void loop(){
while(true){
mFunc();
}
}
}

class Callable{
MongoClient db;
Caller caller;

this(){
db = connectMongoDB("127.0.0.1");
foo();
caller = new Caller();
}

~this(){
db.cleanupConnections();
}

void foo(){
writeln("Started");
auto result = 
db.getCollection("test.collection").findAndModify([

"state": "running"],
["$set": ["state": "stopped"]
]);
writeln(result);
writeln("Finished");
}
}



Output:
Started

{"_id":"5ff6705e21e91678c737533f","state":"running","knowledge":true}

Finished
Started


Re: Member variables in method are null when called as delegate from thread

2021-01-11 Thread Tim via Digitalmars-d-learn

On Monday, 11 January 2021 at 08:21:21 UTC, Arafel wrote:
It's also possible that you'll have to make Foo itself 
`shared`, or at least convert your constructor into a `shared 
this ()` to get a shared instance that you can pass to a 
different thread, but I'm not sure how function pointers / 
delegates work across threads.


Best,

A.


Thanks for that. I'll give it a go and see how that fares


Re: Member variables in method are null when called as delegate from thread

2021-01-10 Thread Tim via Digitalmars-d-learn
Ok, so it seems that it isn't null now. But I stall can't call 
db.getCollection().findAndModify() from vibe.d successfully here. 
Works just fine in the constructor. When it's called form the 
MessengerService thread it never returns from the function call


Member variables in method are null when called as delegate from thread

2021-01-10 Thread Tim via Digitalmars-d-learn

Hi there,

I have something like this:

class Foo{
MongoClient db;

this(){
db = connectMongoDB("127.0.0.1");
void delegate()[string] commands = ["start": ];
MessageService messenger = new MessageService(8081, commands);
}

void start(){
// Do something with db
}

MessageService is a thread that deals with socket communication. 
When a command comes in, it calls the appropriate delegate given 
to it by commands. When MessageService calls the delegate for 
start, db is null. If I call start() in the Foo constructor it 
works just fine. Am I missing something here? Do delegates get 
called outside of their class context? I know I could just pass 
the db into start but I want to work out exactly why this is 
happening


Thanks in advance


Re: Dub platform probes

2020-05-27 Thread Tim via Digitalmars-d-learn

On Wednesday, 27 May 2020 at 21:17:54 UTC, Andre Pany wrote:
I read through the source code. The probe file is created here 
https://github.com/dlang/dub/blob/master/source/dub/compilers/utils.d#L296
The function getTempFile determines a new random temp file name 
and stores the file path in a global variable. A module 
destructor loops through this string array list and deletes the 
temp files 
https://github.com/dlang/dub/blob/master/source/dub/internal/utils.d#L98


I wonder why in your case the temp files are not deleted.

Kind regards
Andre


Me too. I have noticed that sometimes I don't need to and other 
times I do. Maybe it is to do with program crashes where it isn't 
cleaned up? I'll keep a closer eye on it




Re: Dub platform probes

2020-05-26 Thread Tim via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 09:17:52 UTC, Andre Pany wrote:

Hi,
What version of dub do you use? I am not 100 % sure but thought 
platform probes do not longer write files with recent dub 
version.

Do you use DMD or LDC or GDC?

Kind regards
Andre


Hi there

I'm using Dub 1.19.0-1build2 with dmd

Thanks


Dub platform probes

2020-05-25 Thread Tim via Digitalmars-d-learn

Hi all

I end up with a directory flooded with platform probes. How can I 
make sure that old ones are deleted automatically?


Thanks


Re: Asserting that a base constructor is always called

2020-05-24 Thread Tim via Digitalmars-d-learn

On Sunday, 24 May 2020 at 00:51:17 UTC, Jonathan M Davis wrote:
On Saturday, May 23, 2020 4:43:04 PM MDT Tim via 
Digitalmars-d-learn wrote:
It is but I want to make sure for other cases in the future 
where I create a new class that inherits from GameObject. This 
was I can avoid future bugs by ensure that all classes in the 
future that inherit from GameObject, call it's constructor


The base class constructor will _always_ be called. There's no 
need to worry about it. Even if you hadn't declared one, the 
compiler will provide a default constructor, because classes 
have to have a constructor. And if you had declared a 
constructor in your base class but no default constructor, then 
you'd get a compile-time error if your derived class' 
constructor didn't explicitly call it.


- Jonathan M Davis


Oh right. I mean it makes sense but I got confused when super() 
is valid syntax. Why would you need to call the super constructor 
when it's called automatically?


Re: Asserting that a base constructor is always called

2020-05-23 Thread Tim via Digitalmars-d-learn

On Saturday, 23 May 2020 at 22:15:49 UTC, Ali Çehreli wrote:
Is it not already called? I tried the following and it seems to 
work:


import std.stdio;

GameObject[1] world;
enum layer = 0;

/// Base class of most objects in the game
class GameObject{
  this(){
world[layer] = this;
writeln("called");
  }

  abstract void update(){}

  void draw(){}
}

class A : GameObject {
  this(int i) {
writeln(__FUNCTION__);
  }

  override void update() {
  }
}

void main() {
  auto a = new A(42);
}

Ali


It is but I want to make sure for other cases in the future where 
I create a new class that inherits from GameObject. This was I 
can avoid future bugs by ensure that all classes in the future 
that inherit from GameObject, call it's constructor


Asserting that a base constructor is always called

2020-05-23 Thread Tim via Digitalmars-d-learn

I have a base class GameObject:

/// Base class of most objects in the game
class GameObject{
this(){
world[layer] = this;
}

abstract void update(){}

void draw(){}
}

I want to make sure that whenever a class inherits from this, the 
base constructor is always called. Either that or have an 
assertion that gives an error if it isn't called.


Thanks


Re: Storing a reference to the calling object

2020-05-23 Thread Tim via Digitalmars-d-learn

On Saturday, 23 May 2020 at 09:48:57 UTC, Mike Parker wrote:
Since you're using classes, one way is to use a common base 
class or an interface. But assuming "parent" is the owner of 
the Sprite instance, you might eliminate the dependency on the 
parent and have it update the Sprite's position when it's 
updated instead of maintaining a position separately.


class Parent {
   private Sprite sprite;

   void updatePosition(int x, int y)
   {
   sprite.x = x;
   sprite.y = y;
   }
}


Thanks a lot for this. I was trying not to overcomplicate things 
this early in development but I think in me holding back I made 
things more complex then they needed to be.


Storing a reference to the calling object

2020-05-23 Thread Tim via Digitalmars-d-learn
Hi all, I'm a little new to D and I'm wondering how I can store a 
reference to the calling object. I want to create a reference to 
an object's parent so that each time I go to update the sprite, 
it is able to grab its position from the parent.


So if I have:

class Sprite{
/// Postional components of the sprite
int* x, y;
SDL_Surface* image_surface;
auto parent;

this(const char* path, auto parent){
writeln(*x);
this.parent = parent;
}

void update(){
// Copy loaded image to window surface
writeln("Sprites x: ",  *x);
SDL_Rect dstRect;
dstRect.x = parent.x;
dstRect.y = parent.y;
SDL_BlitSurface(image_surface, null, g_surface, );
}
}

And call it like so:

sprite = new Sprite(path, this);

How can I make this sort of thing work? Thanks a lot in advance 
for the help!




Initialization sequence of runtime environment

2014-06-13 Thread Tim via Digitalmars-d-learn
I recently posted another thread (regarding crt1.o: could not 
read symbols: Bad value - I'm creating a new thread because it's 
another problem) and I figured out that the following error:


stack_bottom = 7fc98804ae18 thread_stack 0x4
/usr/sbin/mysqld(my_print_stacktrace+0x35)[0x8cea15]
/usr/sbin/mysqld(handle_fatal_signal+0x4a4)[0x65e0d4]
/lib64/libpthread.so.0(+0xf710)[0x7fc98abcb710]
/usr/lib64/libphobos2.so.0.65(gc_malloc+0x29)[0x7fc951a70e05]

... occures when I never call rt_init()/rt_term() (or 
Runtime.initialize()/Runtime.terminate()). That solved the 
problem and I can successfully execute all my D-code.


I'm using the shared library as UDF in MySQL. My current code 
looks as follows:


export extern(C){
	my_bool mysql_d_udf_init(UDF_INIT *initid, UDF_ARGS *args, char 
*message)

{
return (rt_init() ? 0 : 1);
}

void mysql_d_udf_deinit(UDF_INIT *initid)
{
rt_term();
}

	char* mysql_d_udf(UDF_INIT* initid, UDF_ARGS* args, char* 
result, c_ulong *length, char* is_null, char* error)

{
string res = Hello World!;
result = cast(char*) res.ptr;

*length = res.length;

return cast(char*) result;
}
}

When I register the function in MySQL and execute select 
mysql_d_udf() everything works fine. I'm receiving Hello 
World! and everything is fine. But when I try to restart the 
server, the server is not responding. I've to kill the server 
manually which is impracticable in productional environment.


I first thought that rt_term() throws an exception (or something 
else) that prevents the MySQL server from being restartet 
gracefully. So I removed rt_term() from my deinit()-function. But 
that didn't solve the problem. When I also remove rt_init() I'm 
getting the gc_malloc-exception as described above. So it seems 
that rt_init() registers/enables something I'm unable to release 
I don't know exactly. Fact is that I see no exception or log 
entry in my MySQL log and the server restarts successfully 
without my D-based UDF plugin. So something seems to be wrong...


I don't know if my initialization of the D-runtime environment is 
correct? I sometimes read something about gc_init() (but I 
thought rt_init()/Runtime.initialize() handles that for me...). 
Any suggestions how to initialize/terminate the runtime 
environment in shared libraries? Probably I'm doing something 
wrong...


If there's no solution, I've to write the UDF functions using C 
(I don't prefer that way because all other projects are D-based).


Re: crt1.o: could not read symbols: Bad value

2014-06-12 Thread Tim via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 17:21:54 UTC, Tim wrote:

On Wednesday, 11 June 2014 at 17:11:51 UTC, Tim wrote:

On Wednesday, 11 June 2014 at 10:09:50 UTC, FreeSlave wrote:
I conclude that because I have similar errors when trying to 
build 64-bit library on 32-bit system.


/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(format_712_5b3.o): 
relocation R_X86_64_32 against `.rodata' can not be used when 
making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libphobos2.a: error adding symbols: 
Bad value

collect2: error: ld returned 1 exit status
--- errorlevel 1

But paths in your error log look like you're on x64, so it's 
probably not the case.


Yes, I'm using a x64 system (CentOS 6.5), but I also use dmd64.


It seems that -defaultlib=libphobos2.so solved the problem. 
When I use the following compile command:


dmd test.d -shared -defaultlib=libphobos2.so

I don't get any error. I hope the shared object works as 
expect...


I can compile my so-library (which contains MySQL UDF Functions). 
It also works - as long as I try to create objects or assign 
something like this:


export extern(C):
char* mysql_custom_udf(UDF_INIT* initid, UDF_ARGS* args, char* 
result, c_ulong *length, char* is_null, char* error)

{

JSONValue json = null;

	json = [myObject : AssignSomething]; // - That throws the 
exception


string res = Hello World!;
result = cast(char*) res.ptr;

*length = res.length;

return cast(char*) result;

}

The function above is contained inside the shared object (so) 
file. When I remove/comment out the json = [myObject : 
AssignSomething];-line I can call the udf from MySQL. But when 
I uncomment/insert the line I'm getting the following error:


Thread pointer: 0x1d24250
Attempting backtrace. You can use the following information to 
find out
where mysqld died. If you see no messages after this, something 
went

terribly wrong...
stack_bottom = 7fc98804ae18 thread_stack 0x4
/usr/sbin/mysqld(my_print_stacktrace+0x35)[0x8cea15]
/usr/sbin/mysqld(handle_fatal_signal+0x4a4)[0x65e0d4]
/lib64/libpthread.so.0(+0xf710)[0x7fc98abcb710]
/usr/lib64/libphobos2.so.0.65(gc_malloc+0x29)[0x7fc951a70e05]

Any suggestions how to solve that error? It seems that there's 
anything wrong with gc_malloc in libphobos2...


Re: Decimal type documentation

2014-06-11 Thread Tim via Digitalmars-d-learn

On Tuesday, 10 June 2014 at 15:52:29 UTC, Poyeyo wrote:
Hello, has anyone used this 
https://github.com/andersonpd/decimal implementation?


I'm learning D and want to know where to start for the decimal 
(or bigfloat) stuff.


The goal is to be able to read and write some data from a SQL 
DB with a decimal(10,2) field.


I recently tried this implementation without any success. I 
always got conflicts.


I had the same problem. I had to read a decimal(32,8) value from 
my database. I figured out that the best solution for my case is 
to simply use the phobos implementation for BigInt. I'm simply 
converting the decimal-value to an integer (using multiplication) 
and use this instead of solving all the conflicts of the library 
above.


Re: crt1.o: could not read symbols: Bad value

2014-06-11 Thread Tim via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 10:09:50 UTC, FreeSlave wrote:
I conclude that because I have similar errors when trying to 
build 64-bit library on 32-bit system.


/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(format_712_5b3.o): 
relocation R_X86_64_32 against `.rodata' can not be used when 
making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libphobos2.a: error adding symbols: 
Bad value

collect2: error: ld returned 1 exit status
--- errorlevel 1

But paths in your error log look like you're on x64, so it's 
probably not the case.


Yes, I'm using a x64 system (CentOS 6.5), but I also use dmd64.


Re: crt1.o: could not read symbols: Bad value

2014-06-11 Thread Tim via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 17:11:51 UTC, Tim wrote:

On Wednesday, 11 June 2014 at 10:09:50 UTC, FreeSlave wrote:
I conclude that because I have similar errors when trying to 
build 64-bit library on 32-bit system.


/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(format_712_5b3.o): 
relocation R_X86_64_32 against `.rodata' can not be used when 
making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libphobos2.a: error adding symbols: 
Bad value

collect2: error: ld returned 1 exit status
--- errorlevel 1

But paths in your error log look like you're on x64, so it's 
probably not the case.


Yes, I'm using a x64 system (CentOS 6.5), but I also use dmd64.


It seems that -defaultlib=libphobos2.so solved the problem. When 
I use the following compile command:


dmd test.d -shared -defaultlib=libphobos2.so

I don't get any error. I hope the shared object works as expect...


crt1.o: could not read symbols: Bad value

2014-06-10 Thread Tim via Digitalmars-d-learn

Hi guys,

I've the following few lines:


module test;

export:
extern(D):


int test()
{
return 0;
}

... and compile it using the following line:

dmd -m64 -fPIC -L-shared test.d -oflibtest.so

But when I try to compile it, I always get the following error:

/usr/bin/ld: 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: 
relocation R_X86_64_32S against `__libc_csu_fini' can not be used 
when making a shared object; recompile with -fPIC
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: 
could not read symbols: Bad value

collect2: ld gab 1 als Ende-Status zurück
--- errorlevel 1

Any suggestions how to solve the problem?


Re: crt1.o: could not read symbols: Bad value

2014-06-10 Thread Tim via Digitalmars-d-learn

On Tuesday, 10 June 2014 at 20:29:56 UTC, FreeSlave wrote:

dmd has -shared option. Try it instead of -L-shared.


I'm getting a similar error:

/usr/bin/ld: 
/usr/local/bin/../lib64/libphobos2.a(object__a_58c.o): relocation 
R_X86_64_32 against `_D10TypeInfo_m6__initZ' can not be used when 
making a shared object; recompile with -fPIC
/usr/local/bin/../lib64/libphobos2.a: could not read symbols: Bad 
value

collect2: ld gab 1 als Ende-Status zurück
--- errorlevel 1


How to handle try-catch blocks, nothrow and logfiles

2014-05-24 Thread Tim via Digitalmars-d-learn
I'm working on an application where I want log all exceptions but 
I'm not sure what's the best way to realize that. Sure I can do 
the following:


void myMethod() nothrow
{
   try
   {
 // Do something
   }
   catch (Exception e)
   {
 // Write log file
   }
}

But there are some problems:
   1) try-catch are working great for local error handling. But 
they are nearly useless for global error handling. Imagine I've 
an application where I want log all thrown exceptions. Sure, I 
can create a Logfile-class and log all exceptions in the 
catch-block. But doing this in all my methods forces me to create 
dirty code (more braces, more idents because of more braces, more 
lines and so on...). Additionally when I change the interface of 
my Logfile-class I need to adapt all catch-blocks. I think that's 
not an optimal solution. So, is there anything I can use to log 
all exceptions in one handler, for instance something like that:


void handleExceptions(Exception e)
{
   // Write to log file
}

void myMethod() throwTo(handleExceptions)
{
   // Call something that probably throws an exception
}

   2) When I want create an application where all methods are 
defined as nothrow - how can I realize that? Writing to a 
log-file is already throwable. Yes, I can catch the exception and 
write the same to the command line but that's also unsafe... are 
there any nothrow-function to write a file or something to the 
command line? It's a bit sad when I want log an exception and I'm 
unable to write the log entry because something happened. So how 
can make sure that I log all exceptions? Is that even possible?


Re: How to handle try-catch blocks, nothrow and logfiles

2014-05-24 Thread Tim via Digitalmars-d-learn

On Saturday, 24 May 2014 at 17:55:07 UTC, Ali Çehreli wrote:

On 05/24/2014 10:09 AM, Tim wrote:

 I'm working on an application where I want log all exceptions
but I'm
 not sure what's the best way to realize that.

A common solution is to log it in the exception class'es 
constructor. We even dump the backtrace with libunwind in our 
C++ application.


But this only works for my own exceptions, right? I don't see any 
way to log exceptions in the constructor for phobos-function 
which are also able to throw exceptions.




However, you may quickly realize that not every thrown 
exception is log-worthy. The reason is, e.g. a MyMissingFile 
exception may not be important when there is a default action 
to follow. No need to log in that case.




That's right. It's not necessary to log all exceptions but using 
a global exception handler wouldn't prevent me from handling such 
exception in my method so that no exception is generated. It 
would be nice to have something like Exception, Warning and Info 
to determine if it's necessary to log it.


Re: Modify char in string

2014-05-19 Thread Tim via Digitalmars-d-learn

On Sunday, 18 May 2014 at 19:09:52 UTC, Chris Cain wrote:

On Sunday, 18 May 2014 at 18:55:59 UTC, Tim wrote:

Hi everyone,

is there any chance to modify a char in a string like:


As you've seen, you cannot modify immutables (string is an 
immutable(char)[]). If you actually do want the string to be 
modifiable, you should define it as char[] instead.


Then your example will work:

void main()
{
   char[] sMyText = Replace the last char_;
   sMyText[$ - 1] = '.';
}

If you actually want it to be immutable, you can still do it, 
but you can't modify in-place, you must create a new string 
that looks like what you want:


void main()
{
   string sMyText = Replace the last char_;
   sMyText = sMyText[0 .. $-1] ~ .;
   // you would do
   //sMyText[0 .. 5] ~ . ~ sMyText[6..$];
   // to replace something in the 5th position
}

Note that the second method allocates and uses the GC more 
(which is perfectly fine, but not something you want to do in a 
tight loop). For most circumstances, the second method is good.


Thanks - I already tried:

 void main()
 {
char[] sMyText = Replace the last char_;
sMyText[$ - 1] = '.';
 }

but I always getting Error: cannot implicitly convert expression 
(Replace the last char_) of type string to char[]. I know, I 
can use cast(char[]) but I don't like casts for such simple 
things...


Modify char in string

2014-05-18 Thread Tim via Digitalmars-d-learn

Hi everyone,

is there any chance to modify a char in a string like:

void main()
{
   string sMyText = Replace the last char_;
   sMyText[$ - 1] = '.';
}

But when I execute the code above I'm always getting cannot 
modify immutable expression at sMyText[__dollar -1LU]. I though 
D supported such modifications anytime. How can I do that now...?


Re: Socket server + thread: cpu usage

2014-05-01 Thread Tim via Digitalmars-d-learn

On Tuesday, 29 April 2014 at 17:19:41 UTC, Adam D. Ruppe wrote:

On Tuesday, 29 April 2014 at 17:16:33 UTC, Tim wrote:

Is there anything I'm doing wrong?


You should be using a blocking socket. With them, the operating 
system will put your thread on hold until a new connection 
comes in. Without them, it will endlessly loop doing absolutely 
nothing except checking if a new connection is there yet. 
Horribly, horribly inefficient.


Blocking sockets are now working as expected, but I've one 
problem. When I do the following in my server-accept-thread:


while (m_oSocket.isAlive)
{
oSocketSet.reset();
oSocketSet.add(m_oSocket);

	nAcceptedSockets = Socket.select(oSocketSet, null, null, 
25.msecs);


if (nAcceptedSockets  0)
{
// Do something...
}

}

... and the following in my client:

void connect()
{
m_oSocket = new TcpSocket(AddressFamily.INET);
m_oSocket.connect(new InternetAddress(127.0.0.1, 12345));
}

The CPU usage is low as long as my connect is connected. When I 
disconnect the client using the following few lines:


void disconnect()
{
m_oSocket.shutdown(SocketShutdown.BOTH);
m_oSocket.close();
}

... the CPU usage goes up. I think that SocketShutdown.BOTH 
causes Socket.select to fail which results in an endless loop. 
Any suggestions how to handle that problem?


@Ali Çehreli: Thanks, didn't know that UFCS can also handle such 
constructs :)


Re: Socket server + thread: cpu usage

2014-05-01 Thread Tim via Digitalmars-d-learn

On Thursday, 1 May 2014 at 08:08:37 UTC, Tim wrote:

On Tuesday, 29 April 2014 at 17:19:41 UTC, Adam D. Ruppe wrote:

On Tuesday, 29 April 2014 at 17:16:33 UTC, Tim wrote:

Is there anything I'm doing wrong?


You should be using a blocking socket. With them, the 
operating system will put your thread on hold until a new 
connection comes in. Without them, it will endlessly loop 
doing absolutely nothing except checking if a new connection 
is there yet. Horribly, horribly inefficient.


Blocking sockets are now working as expected, but I've one 
problem. When I do the following in my server-accept-thread:


while (m_oSocket.isAlive)
{
oSocketSet.reset();
oSocketSet.add(m_oSocket);

	nAcceptedSockets = Socket.select(oSocketSet, null, null, 
25.msecs);


if (nAcceptedSockets  0)
{
// Do something...
}

}

... and the following in my client:

void connect()
{
m_oSocket = new TcpSocket(AddressFamily.INET);
m_oSocket.connect(new InternetAddress(127.0.0.1, 12345));
}

The CPU usage is low as long as my connect is connected. When I 
disconnect the client using the following few lines:


void disconnect()
{
m_oSocket.shutdown(SocketShutdown.BOTH);
m_oSocket.close();
}

... the CPU usage goes up. I think that SocketShutdown.BOTH 
causes Socket.select to fail which results in an endless loop. 
Any suggestions how to handle that problem?


@Ali Çehreli: Thanks, didn't know that UFCS can also handle 
such constructs :)


Small correction: The CPU usage is low as long as my client is 
connected. When I disconnect the client using the following few 
lines:


Socket server + thread: cpu usage

2014-04-29 Thread Tim via Digitalmars-d-learn

Hi guys,

I've the following snipped:

TcpSocket oSocket = new TcpSocket(AddressFamily.INET);
oSocket.bind(new InternetAddress(127.0.0.1, 12345));
oSocket.blocking(false);
oSocket.listen(0);

while(true)
{
try
{
Socket oRequestSocket = oSocket.accept();

Request oRequest = new Request(oRequestSocket);
oRequest.start(); // Start request thread
}
catch (SocketAcceptException oException)
{
Thread.yield();
}
}

When I execute the code above, the while(true)-loop uses nearly 
100% (1 complete cpu). When I connect to the server multiple 
times (note that each Request-Thread has it's own 
while(oRequestSocket.isAlive)-loop) the cpu usage easily reaches 
120, 130... 200 and more cpu usage.


Is there anything I'm doing wrong? I don't want use blocking 
sockets... how to handle 100 or 1000 connections when the main 
server thread already consumes 1 cpu?


Re: Socket server + thread: cpu usage

2014-04-29 Thread Tim via Digitalmars-d-learn

On Tuesday, 29 April 2014 at 17:19:41 UTC, Adam D. Ruppe wrote:

On Tuesday, 29 April 2014 at 17:16:33 UTC, Tim wrote:

Is there anything I'm doing wrong?


You should be using a blocking socket. With them, the operating 
system will put your thread on hold until a new connection 
comes in. Without them, it will endlessly loop doing absolutely 
nothing except checking if a new connection is there yet. 
Horribly, horribly inefficient.


Alright, this would solve the server-cpu-usage-problem. But what 
about incoming connections? When I create a new thread and use 
non-blocking socket I've exactly the same problem. I can also 
solve this problem by using blocking sockets, but what happens if 
I do the following:


while(oMyBlockingSocket.isAlive)
{
oMyBlockingSocket.receive(...);
}

... and close the connection on the client side? I would never 
receive anything and receive() waits never comes back or would 
this throw an exception or similar?


Re: Socket server + thread: cpu usage

2014-04-29 Thread Tim via Digitalmars-d-learn

On Tuesday, 29 April 2014 at 17:35:08 UTC, Tim wrote:

On Tuesday, 29 April 2014 at 17:19:41 UTC, Adam D. Ruppe wrote:

On Tuesday, 29 April 2014 at 17:16:33 UTC, Tim wrote:

Is there anything I'm doing wrong?


You should be using a blocking socket. With them, the 
operating system will put your thread on hold until a new 
connection comes in. Without them, it will endlessly loop 
doing absolutely nothing except checking if a new connection 
is there yet. Horribly, horribly inefficient.


Alright, this would solve the server-cpu-usage-problem. But 
what about incoming connections? When I create a new thread and 
use non-blocking socket I've exactly the same problem. I can 
also solve this problem by using blocking sockets, but what 
happens if I do the following:


while(oMyBlockingSocket.isAlive)
{
oMyBlockingSocket.receive(...);
}

... and close the connection on the client side? I would never 
receive anything and receive() waits never comes back or would 
this throw an exception or similar?


Sorry... I totally forgot... I can use SocketSet's as I already 
asked: 
http://forum.dlang.org/thread/ogghezngzrvvoqaod...@forum.dlang.org#post-kivp3e:24jif:241:40digitalmars.com


... but I thought it's also possible using non blocking sockets 
by using Thread.yield().