Pointer error, related to variable scope

I create a struct as a global variable named g_preload_data which contains a member variable hotspot_area in preload.jl. The member variable hotspot_area is initialized by creating a ArchGDAL geometry object.

When I use this variable g_preload_data.hotspot_area in a function in main.jl, there is error. If i create the ArchGDAL object locally, there is no error.


using ArchGDAL
mutable struct SystemPreloadData

   function SystemPreloadData()
       self = new()
       self.hotspot_area = load_area()
       return self

function load_area()
    d = ArchGDAL.read(hotspot_path)
    layer = ArchGDAL.getlayer(d, 0)
    fs = ArchGDAL.getfeature(layer, 1) do f
    return fs
g_preload_data = SystemPreloadData()
  1. Got errors when use the global variable in main.jl as follows
ArchGDAL.contains( g_preload_data .hotspot_area, 
           ArchGDAL.createpoint( 102.1, 0.4) )    # error here

The error message is as follows

ERROR: LoadError: LoadError: GDALError (CE_Failure, code 10):
        Pointer 'hThis' is NULL in 'OGR_G_Contains'.

 [1] gdaljl_errorhandler(::GDAL.CPLErr, ::Int32, ::Cstring) at /home/liye/.julia/packages/GDAL/yPmFi/src/error.jl:36
 [2] ogr_g_contains at /home/liye/.julia/packages/GDAL/yPmFi/src/ogr_api.jl:941 [inlined]
 [3] contains(::ArchGDAL.IGeometry, ::ArchGDAL.IGeometry) at /home/liye/.julia/packages/ArchGDAL/ohMpc/src/ogr/geometry.jl:605
 [4] #read_trj_json#21(::Bool, ::typeof(Hotspot.read_trj_json), ::String) at /mnt/c/julia_dev/mt/hotspot/src/detect_hotspot_json_file.jl:26
 [5] read_trj_json at /mnt/c/julia_dev/mt/hotspot/src/detect_hotspot_json_file.jl:13 [inlined]
 [6] macro expansion at ./util.jl:288 [inlined]
 [7] #detect_hotspot_json_file#26(::Int64, ::Int64, ::Int64, ::String, ::typeof(Hotspot.detect_hotspot_json_file), ::String) at /mnt/c/julia_dev/mt/hotspot/src/detect_hotspot_json_file.jl:105
 [8] (::Hotspot.var"#kw##detect_hotspot_json_file")(::NamedTuple{(:out_dir_base,),Tuple{String}}, ::typeof(Hotspot.detect_hotspot_json_file), ::String) at ./none:0
 [9] top-level scope at util.jl:288
 [10] top-level scope at /mnt/c/julia_dev/mt/hotspot/test/test_debug_data.jl:24
 [11] include at ./boot.jl:328 [inlined]
 [12] include_relative(::Module, ::String) at ./loading.jl:1105
 [13] include(::Module, ::String) at ./Base.jl:3
  1. If call load data function locally, there is no error
hotspot_area = load_area()
ArchGDAL.contains( hotspot_area, 
           ArchGDAL.createpoint( 102.1, 0.4) )    # works well

It would be caused by something related to variable scope. Can any one help? Thanks

g_preload_data = SystemPreloadData()

Does this line happen within a module? If so, it’s probably being precompiled, which will not work if that data structure stores any raw pointers. Instead, you need to construct the pointer in your __init__ function, as discussed in Modules · The Julia Language

1 Like

Your suggestion works. It is solved by putting the code into __init__(). Thank you so much!