array error

Koroskin Denis 2korden at gmail.com
Sun Jul 20 03:57:39 PDT 2008


On Sun, 20 Jul 2008 12:18:18 +0400, hrk <l8atnight at gmail.com> wrote:

> Hi,
>
> I have a class STATUS, in which i do have an dynamic array
>
> class STATUS {
> private:
> int mVector[];
> public:
> int* StatusHandle() {
>     return cast(int*) this.mVector.ptr;
>   }
> bool Errors() {
>     ...
>  }
> int SqlCode() {
> ...
> }
>   int EngineCode() {
> ...
> }
> void Reset() {
>   mVector[] = 0;
> }
> this(int asize) {
>    mVector.length = asize;
>     mVector[] = 0;
> }
>   string ErrorMessage() {
> ...
> }
> }
>
> The method  StatusHandle() returns a pointer that is the input for a  
> function in a “C” DLL.
>
> The class is newed, along with other classes of this kind (STATUS), in  
> an other classes method:
>
> bool Connect(string dbname, string username, string password, string  
> RoleName = "", string CharSet = "") {
>       auto status = new STATUS(200);
> .........
> .........
> cresult = isc_database_info(status.StatusHandle(), &db, 3, cast(char*)  
> items.ptr, 200, result.ResultHandle());
> .........
> .........
> .........
> }
>
> The class (STATUS) instances will function a couple of times, but than  
> they crash unpredictably.
> Can anyone tell me what i am doing wrong? I need the memory of the array  
> (mVector) to be contiguous and it’s content should only change through  
> the manipulation of the pointer  StatusHandle() by the “C” DLL  
> functions. I need sometimes several instances of the class STATUS that  
> are created in some other class.
> I am using 2.0 and phobos.
>

There are a few problems in your code. First of all, string is an  
immutable class by design. You should not cast away its constness.  
Instead, use char[], which is mutable. In fact string is an alias (kindof  
typedef in C++) to invariant(char)[], i.e. an array of immutable chars.

Second, strings (and char[]) are not null-terminated, otherwise strind (or  
any other array) slicing wouldn't work. That's why you should ensure that  
0 is appended to your string. There are two ways to do so:

1) do this but calling toStringz(items): isc_database_info(..., ..., ...,  
toStringz(items), ..., ...);
2) if and only if you are sure that this C function doesn't mutate your  
string, you can append the 0 manually:
items ~= 0;
// you can guarantee that string won't be changed through pointer
isc_database_info(..., ..., ..., cast(char*)items.ptr, ..., ...);

Apart from that I don't see any issue with your STATUS class. Just two  
notes:
- you may declare protection attributes on each class member individually,  
like "private int mVector[];".
- you can declare array like "int mVector[];" as well as "int[] mVector;".


More information about the Digitalmars-d-learn mailing list